Handling Exceptions in Java

Handling Exceptions in Java

·

4 min read

Exception generally means an abnormality. In Java, it is a mechanism of handling errors during runtime.

Types of Runtime Errors

  • ClassNotFoundException

  • IOException

  • SQLException

  • RemoteException

The main advantage of exception handling is to maintain the normal flow of the application. Abnormalities in your code disrupts the normal flow of the application that is why an exception is used in handling errors while compiling the code.

For example: There are 5 statements in the program below and there occurs an exception at statement 3, the rest of the code will not be executed i.e. statement 3 to 5 will not be executed. However, if we perform exception handling, the rest of the statement will be executed.

statement 1;  
statement 2;  
statement 3; //exception
statement 4;  
statement 5;

Root Class of Java Exceptions

The java.lang.Throwable class is the root class of Java Exception hierarchy which is inherited by two subclasses: Exception and Error.

Exception.png

Types of Java Exception

  • Checked Exception

  • Unchecked Exception

  • Error

Differences between Java Exceptions

Checked Exception: The classes which directly inherit Throwable class except RuntimeException and Error are known as checked exceptions e.g. IOException, SQLException. Checked exceptions are checked at compile-time.

Unchecked Exception: The classes which inherit RuntimeException are known as unchecked exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-time, but they are checked at runtime.

Error: Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError.

Keywords in Java Exception

The try keyword is used to specify a block where we should place exception code. The try block must be followed by either catch or finally.

The catch block is used to handle the exception. It must be preceded by try block which means we can't use catch block alone. It can be followed by finally block later.

An Example of Java Exception Handling using the try-catch statement

Handling.png

The finally block is used to execute the important code of the program. It is executed whether an exception is handled or not.

An Example of Java Exception Handling using the finally statement

Handling 2.png

The throw keyword is used to throw an exception.

The throw keyword is used to declare exceptions. It doesn't throw an exception. It specifies that there may occur an exception in the method. It is always used with method signature.