Java Exception Handling

Last Updated On Thursday 11th Nov 2021

Exception handling

Java exception

Java uses exceptions to indicate errors and catches exceptions through try...catch.

  • Put the code that may cause exceptions in try {...}, and then use catch to capture the corresponding Exception and its subclasses.
  • Java’s exception is class and inherited from Throwable.
  • Error is a serious error that does not need to be caught, and Exception is a handleable error that the error should see.
  • RuntimeException does not need to be captured forcibly, non-RuntimeException .
  • Checked Exception needs to be seized forcibly or declared with throws.
  • It is not recommended to catch the exception but not do any processing.

Catch the exception

When using try ... catch ... finally.

  • The matching order of multiple catch statements is very important, and the subclass must be placed first.

  • The finally statement guarantees that it is will execute it with or without exception. It is optional.

  • A catch statement can also match multiple non-inheritance exceptions.

Throw an exception

How to throw an exception

  1. Create an instance of Exception.
  2. Use the throw statement to throw.
	void process2(String s) {
  if (s == null) {
    NullPointerException e = new NullPointerException();
    throw e;
    throw new NullPointerException();
  }
}
	
  • When catching an exception and throwing a new exception again, it should hold the original exception information;

  • Do not usually finally throw exceptions in

NullPointerException

  • NullPointerException is a common logic error in Java code, which should be exposed and fixed early.

  • You can enable the enhanced exception information of Java 14 to view the detailed error information of NullPointerException.