Search code examples
javasqlexceptionsqlexception

Difference between Exception and SQLException


Can someone explain the difference between catching an Exception and catching an SQLException? I know that SQLException will print out more information if you choose to print out the exception errors, but is there anything else?

try {
   //code
} catch(Exception ex) {
   //code
}

And

try {
   //code
} catch(SQLException ex) {
   //code
}

What are the benefits and differences of using Exception and SQLException in the catch block?


Solution

  • This is not the only difference.

    Catching Exception is dangerous because it also catches all RuntimeExceptions (therefore unchecked exceptions), and that include niceties such as NullPointerException etc which are clear programmer errors. Don't do that!

    Also, Exception is a class like any other, so you can subclass it and add constructors/methods of yours. For instance, SQLException has a .getErrorCode() method which Exception does not have. If you only catch Exception, you cannot access this method.

    In general, catching the "more precise" exception first is the best. For instance, with the new (in Java 7...) file API, you can easily distinguish between filesystem level errors and other I/O errors, since FileSystemException extends IOException:

    try {
        something();
    } catch (FileSystemException e) {
        // fs level error
    } catch (IOException e) {
        // I/O error
    }