Exception Handling in Java

The exception is an abnormal condition that occurs during the execution of a program and disrupts the normal flow of the program. This exception must be handled properly. If it is not handled, the program will be terminated abruptly.

Exception Handling in Java is one of the powerful mechanisms to handle the runtime errors so that the normal flow of the application can be maintained. 

In this tutorial, we will learn more about exceptions in java,  types of exceptions, and the difference between checked and unchecked exceptions.

What is Exception Handling?

Exception Handling is a mechanism to handle runtime errors such as IOException, SQLException, ClassNotFoundException, RemoteException, etc.

Major reasons why an exception Occurs

  • Invalid user input
  • Device failure
  • Loss of network connection
  • Physical limitations (out of disk memory)
  • Code errors
  • Opening an unavailable file

Let us discuss the most important part which is the differences between Error and Exception that is as follows: 

Error: An Error indicates a serious problem that a reasonable application should not try to catch.

Exception: Exception indicates conditions that a reasonable application might try to catch.

Java Exceptions - Hierarchy

The java.lang.Throwable class is the root class or base class of the Java Exception hierarchy inherited by two subclasses: One branch is headed by Exception and another branch is headed by Error. The hierarchy of Java Exception classes is given below:





Types of Java Exceptions

Java defines several types of exceptions that relate to its various class libraries. Java also allows users to define their own exceptions.

Exceptions can be Categorized in two ways:
  • Built-in Exception (Checked, Unchecked, and Error)
  • User-Defined Exceptions

Difference between Checked and Unchecked Exceptions

1) Checked Exception

The classes that directly inherit from the Throwable class apart from (except) RuntimeException and Error are known as checked exceptions. For example, IOException, SQLException, FileNotFoundException, etc. Checked exceptions are checked at compile time.

2) Unchecked Exception

The classes that inherit the RuntimeException are known as unchecked exceptions. For example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked at compile time, but they are checked at runtime.

3) Error

Error is irrecoverable. Some example of errors are OutOfMemoryError, VirtualMachineError, AssertionError etc.


Java Exception Keywords

Java has the following keywords that are used in exception handling. 
  1. try- The "try" keyword is used to specify a block where we should place an exception code. It means we can't use try block alone. The try block must be followed by either catch or finally.
  2. catch - The "catch" block is used to handle the exception. It must be preceded by a try block which means we can't use catch block alone. It can be followed by the finally block later.
  3. finally- The "finally" block is used to execute the necessary code of the program. It is executed whether an exception is handled or not.
  4. throw- The "throw" keyword is used to throw an exception.
  5. throws - The "throws" keyword is used to declare exceptions. It specifies that there may occur an exception in the method. It doesn't throw an exception. It is always used with method signature.

Java Exception Handling Example

Let's see an example of Java Exception Handling in which we are using a try-catch statement to handle the exception.

ExceptionHandling1.java
public class ExceptionHandling1 {
public static void main(String args[]) {
try {
//code that may raise exception
int value = 10 / 0;
} catch (ArithmeticException ex) {
System.out.println(ex);
}
//rest of the code
System.out.println("rest of the program...");
}
}
Output:-
java.lang.ArithmeticException: / by zero
rest of the program...
In the above example, 10/0 raises an ArithmeticException which is handled by a try-catch block.

Some of the scenarios of java exceptions

There are given some scenarios where unchecked exceptions may occur. They are as follows:

1) A scenario where ArithmeticException occurs
If we divide any number by zero, there occurs an ArithmeticException.
int value=10/0;  //ArithmeticException  
2) A scenario where NullPointerException occurs
If we have a null value in any variable, performing any operation on the variable throws a NullPointerException.
String data=null;  
System.out.println(data.length()); //NullPointerException  
3) A scenario where NumberFormatException occurs
If the formatting of any variable or number is mismatched, it may result into NumberFormatException. Suppose we have a string variable that has characters; converting this variable into a digit will cause NumberFormatException 
String name="abc";  
int i=Integer.parseInt(name); //NumberFormatException 
4) A scenario where ArrayIndexOutOfBoundsException occurs
When an array exceeds its size, the ArrayIndexOutOfBoundsException occurs. there may be other reasons to occur ArrayIndexOutOfBoundsException. Consider the following statements.
int arr[]=new int[5];  
arr[13]=10; //ArrayIndexOutOfBoundsException