管理 Java 中的异常
我正在做一个小型数据库程序。
Connection connection = DriverManager.getConnection(..., ..., ...);
String createTable= "CREATE TABLE Employee ...";
try
{
Statement stmt = connection.createStatement ();
stmt.executeUpdate(createTable);
stmt.close();
connection.close ();
}
catch(Exception Ex)
{
System.out.println("Erreur : " + Ex.toString());
}
当您运行该程序时,一切都会好起来,但第二次您会收到此异常:
重复的表名称:Employee
好的,我知道如何管理异常,但是如何管理每个可能的异常。就像:
IF
异常是重复错误THEN
显示自定义重复消息。
IF
这是一个重复的主键THEN
显示另一条错误消息,依此类推。
谢谢。
I'm doing a small database program.
Connection connection = DriverManager.getConnection(..., ..., ...);
String createTable= "CREATE TABLE Employee ...";
try
{
Statement stmt = connection.createStatement ();
stmt.executeUpdate(createTable);
stmt.close();
connection.close ();
}
catch(Exception Ex)
{
System.out.println("Erreur : " + Ex.toString());
}
When you run the program everything is going to be fine, but the second time you will get this Exception :
Duplicate table name : Employee
Ok fine I know how to manage Exceptions, but how about managing every possible Exception. Like :
IF
the Exception is a Duplicattion error THEN
display a custom Duplicate message.
IF
it's a duplicate primary key THEN
display another error message and so on.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果要处理特定异常,则需要多个 catch 语句。
You need multiple catch statements if you want to handle specific exceptions.
您必须解析异常方法字符串才能获取实际 SQL 异常的“子类型”:
You'll have to parse the exceptions method string to get the "subtype" of the actual SQL exception:
如果您使用 Spring JDBC 库,它会为您做一些异常转换,因此您将得到(未经检查的)异常,例如
DuplicateKeyException
、TypeMismatchDataAccessException
等,您可以将这些异常转换为 Spring JDBC 库。可以单独抓。If you use the Spring JDBC library, it will do some exception translation for you, so you'll get (unchecked) exceptions like
DuplicateKeyException
,TypeMismatchDataAccessException
, etc., which you can catch separately.您还可以通过根据 SQLException 的错误代码定义特定行为来为 sql-Exception 排序正确的错误处理。但请注意:错误代码是特定于实现的,这意味着例如 JavaDB 的一个错误代码如果来自另一个 dbms,则不具有相同的含义。
看
JAVA API 中的 SQLException.getErrorCode()
You could also sort the right error handling for you sql-exception by defining a specific behavior depending on the error-code of the SQLException. But watch out: the error codes are implementation specific, that means one error code of for example JavaDB does not have the same meaning if it comes from another dbms.
see
SQLException.getErrorCode() in the JAVA API