开发者

Manage Exceptions in Java

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开发者_JS百科 :

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.


You need multiple catch statements if you want to handle specific exceptions.

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
}


You'll have to parse the exceptions method string to get the "subtype" of the actual SQL exception:

 try {
   // ...
 } catch (SQLException e) {
  if (e.getMessage().toLowerString().contains("duplicate table name")) {
   // handle duplicate table name problem
  } else if ( /* ... */ ) {
   // ...
  }
 }


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜