0

我正在做一个小型数据库程序。

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());
}  

当你运行程序时,一切都会好起来的,但第二次你会得到这个异常:

重复的表名:员工

好的,我知道如何管理异常,但是如何管理每个可能的异常。像 :

IF异常是重复错误THEN显示自定义重复消息。

IF这是一个重复的主键THEN显示另一个错误消息等等。

谢谢。

4

4 回答 4

4

如果要处理特定异常,则需要多个 catch 语句。

try {
    // some code that may throw an exception
}
catch (DuplicateKeyException e) {
    // handle a duplicate key exception
}
catch (DuplicateTableException e) {
    // handle a duplicate table exception - note this probably isn't the correct exception, you'll need to look up what is actually thrown
}
catch (Exception e) {
    // handle all other exceptions in a non-specific way
}
于 2011-07-01T10:34:17.607 回答
2

您必须解析异常方法字符串以获取实际 SQL 异常的“子类型”:

 try {
   // ...
 } catch (SQLException e) {
  if (e.getMessage().toLowerString().contains("duplicate table name")) {
   // handle duplicate table name problem
  } else if ( /* ... */ ) {
   // ...
  }
 }
于 2011-07-01T10:35:03.470 回答
0

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.

于 2011-07-01T11:07:15.090 回答
0

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

于 2011-07-01T11:22:27.683 回答