Exception - nhanngh/document GitHub Wiki

What Is an Exception?

  • An exception is an event, which occurs during the execution of a program, that disrupts normal flow of the program's instructions.

Hierarchy of Java Exception classes

hierarchy-of-exception-handling

The Three Kinds of Exceptions:

  1. Checked Exception
  1. Error
  • These are exceptional conditions that are external to the application, and that the application usually cannot anticipate or recover from.(errors can raise from hardware or system malfunction)
  • considered as the unchecked exception
  1. Unchecked Exception
  • Unchecked exceptions and Error are not checked at compile-time, but they are checked at runtime.
  • For example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc.
  • The classes that inherit the RuntimeException

Catching and Handling Exceptions

There are two techniques to write an exception handler: try, catch and finally blocks - try-with-resources

  • The try, catch and finally blocks
    • The try block: You can put each line of code that might throw an exception within its own try block and provide separate exception handlers for each.
    • The catch block:
      • You associate exception handlers with a try block by providing one or more catch blocks directly after the try block.
      • Exception class must be the name of a class that inherits from the Throwable class
      • In Java SE 7 and later, a single catch block can handle more than one type of exception.
    • The finally Block:
      • The finally block always executes when the try block exits.
      • This ensures that the finally block is executed even if an unexpected exception occurs.
      • The finally block may not execute if the JVM exits while the try or catch code is being executed.
      • Use a try-with-resources statement instead of a finally block when closing a file or otherwise recovering resources
  • The try-with-resources statement
    • is a try statement that declares one or more resources, and a resource is an object that must be closed after the program is finished with it.
    • Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.
    • they will be closed regardless of whether the try statement completes normally or abruptly
    • These are reason to use try-with-resources for close resources instead use finally block:
      • More readable code and easy to write.
      • resource leak

use try finally to close resources

use try-with-resource to close resources You can retrieve these suppressed exceptions by calling the Throwable.getSuppressed method from the exception thrown by the try block.

Specifying the Exceptions Thrown by a Method:

  • use throws clause to the method
  • throws checked exception, unchecked exception