Java - Exception (Closeable)

1 - About

The Java mechanism for handling exceptions uses try and catch blocks. With Java, if a method throws an exception, there needs to be a mechanism to handle it (if it's not a Runtime (ie Unchecked) Exception). Generally, a catch block catches the exception and specifies the course of action in the event of an exception, which could simply be to display the message.

In production code, it is not recommended to dump stack traces that are visible to the user.

3 - Management

3.1 - Type

3.1.1 - Checked

Extend Exception

3.1.2 - UnChecked

Extend RuntimeException

When the exception is Unchecked, you avoid the parsing error:

Unhandled exception

3.2 - try (Closeable)

The try block may get Autcloseable object that will be closed at the end of the block

Example:


try (Connection sqlConnection = Driver.getConnection()) {
 
} // the connection will be close when the end of the block is reached

Other way to deal with closeable object org/apache/calcite/util/Closer (similar to com.google.common.io.Closer)


try (Closer closer = new Closer()) {
    closer.add(CloseableObject1);
    closer.add(CloseableObject2);
    ...
}

3.3 - Catch


try {

} catch (ExceptionType name) {

} catch (NoSuchMethodException | IOException | IllegalAccessException | ClassNotFoundException e) {

} finally {

}

3.4 - Throw

All methods use the throw statement to throw an exception.


throw someThrowableObject;
// Example with an exist Exception
throw new FileNotFoundException("Your Message");
throw new IllegalArgumentException("Your Message");

The Throwable class is the superclass of all errors and exceptions in the Java language. Only objects that are instances of this class (or one of its subclasses) are thrown by the Java Virtual Machine or can be thrown by the Java throw statement.

3.5 - Create


public class InvalidTypeException extends Exception {

  public InvalidTypeException(String message){
     super(message);
  }

}

4 - logException


public void logException(SQLException ex) {
    while (ex != null) {
        ex.printStackTrace();
        ex = ex.getNextException();
    }
}

5 - Support

5.1 - java.lang.nullpointerexception

To deal with this exception, you have first to check the reference of object with null


if (myObject != null) {
     System.out.println("NOT NULL");
} else {
     System.out.println("NULL");
}

of use optional in java 8. See Tired of Null Pointer Exceptions? Consider Using Java SE 8's Optional!


Data Science
Data Analysis
Statistics
Data Science
Linear Algebra Mathematics
Trigonometry

Powered by ComboStrap