Exception Handling in Java

To make robust and well-behaved application, Java offers exception handling mechanism using which you can maintain the normal execution control flow when an exception occurs.

What is Exception?

An exception is an error that happens when an application is running. When an unexpected condition arises, the exception is thrown, and it changes the normal execution flow of the program. Java offers a very good system for exception handling.

What do you mean by exception handling?

In a program, if you perform an operation that causes an exception that is an exception is thrown, you can always catch the exception and deal with it. This is called Exception Handling. The Java exception-handling mechanism contains five keywords: try, catch, throw, throws, and finally.

Exception Tree or Hierarchy in Java

Exception Handling in Java

Checked Exceptions

  • Checked exceptions are those exceptions that a programmer must handle it in the code using try...catch block otherwise the code will not compile.
  • These exceptions are the subclasses of the Exception class or one of its subclasses, excluding the RuntimeException subtree.
  • Example of checked exceptions are FileNotFoundException, ClassNotFoundException, etc.
  • When a checked exception is expected, either declare it in the throws clause of your method or catch it in the body of your method.

Runtime Exceptions

  • Runtime Exceptions are also known as Unchecked Exceptions.
  • Runtime Exception occurs when a programmer writes an inappropriate piece of code while programming. For example, ArrayIndexOutOfBoundsException is thrown when you try to access an array element from a position that does not exist.
    public class Test{
    	public static void main(String args[]){
    		int[] scores = {75, 86};
    		scores[2] = 50; // This line will throw ArrayIndexOutOfBoundsException
    	}
    }
  • All the runtime exceptions are a subclass of java.lang.RuntimeException.
  • Example of Runtime Exceptions are ArrayIndexOutOfBoundsException, NullPointerException, ClassCastException, etc.
  • You can also catch runtime exceptions by using try...catch block. It is shown in the below example-
    public class Test{
    	public static void main(String args[]){
    		int[] scores = {75, 86};
    		try{
    			scores[2] = 50; // This line will throw ArrayIndexOutOfBoundsException	
    		}catch(ArrayIndexOutOfBoundsException e){
    			System.out.prinln("Exception");
    		}		
    	}
    }

Errors

  • The error is an exception thrown by JVM due to an error in the environment that process our code.
  • All errors are a subclass of java.lang.Error class.
  • NoClassDefFoundError, StackOverflowError, etc. are examples of Errors.
  • You can catch errors as well but it is recommended that JVM must handle the error itself.