Java - Exception

> Procedural Languages > Java

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.

Advertising

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 - Catch

try {
 
} catch (ExceptionType name) {
 
} catch (NoSuchMethodException | IOException | IllegalAccessException | ClassNotFoundException e) {
 
} finally {
 
}

3.3 - 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.4 - 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!

Advertising
lang/java/exception.txt · Last modified: 2019/07/01 10:08 by gerardnico