Table of Contents

Java - Exception (Closeable)

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.

Management

Type

Checked

Extend Exception

UnChecked

Extend RuntimeException

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

Unhandled exception

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 apache/calcite/blob/master/core/src/main/java/org/apache/calcite/util/Closer.java (similar to com.google.common.io.Closer)

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

Catch

try {

} catch (ExceptionType name) {

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

} finally {

}

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.

Create

public class InvalidTypeException extends Exception {

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

}

logException

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

Support

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!