Search code examples
javasqldatabaseexceptionthrow

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 :

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.


Solution

  • 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 ( /* ... */ ) {
       // ...
      }
     }