Java Exception Handling Complete Tutorial

In this article, we will learn about Exceptions and Exception Handling techniques…

What is Exception

Exception in normal words is an abnormal condition / error.Β  As almost everything in java is a object so asΒ  java exception. It is an object that describes an exceptional condition that has occurred in a piece of code. When an exception condition arises, an object representing that exception is created and thrown in the method that caused the error.

It is an event which disrupts the normal flow of program and object is thrown at runtime.

It is to be noted that, when an exception is occurred at one line of the program the complete program could not complete and terminates except when exception is handled.

Exception Handling in Java

Java exception handling can be done using five keywords

  • try
  • catch
  • throw
  • throws
  • finally

Exception handling in java is one of the important feature which helps in maintaining the normal flow of program.

Program statements that you want to monitor for exception are written inside try block. If exception occurs in try block then it is caught by catch block So only those exceptions can be handled which are getting occured in the program written inside the try block. System generated exception are automatically thrown by JVM.

Once the exception is occured in the code, written in try block , the exception object is thrown by JVM and it gets caught by catch block. That means program flows go to the respective catch block.

There may be cases, where you explicitly want to throw some exception (Custom exception, Pre-defined exception) depending upon situations. To manually throw an exception you can use throw keyword to forcefully throw an exception.

Any exception thrown out of method must be specified as such by throws keyword. Throws keyword declares the exceptions which can be occured in the respective method. This keyword is also used for exception propagation, which we will learn later in this article.

The code that needs to be executed either exception is occurred or not needs to be placed in the finally block.Β  E.g. the code like closing the connection,Β  nullify the array or any other variable should be placed in the finally block.

Try catch must be followed by either catch , finally or both. try block can not be used alone.

This is general form of an exceptional handling block:

try
{
}
catch(ExceptionType1 obj)
{
}
catch(ExceptionType2 obj)
{
}
finally
{
}

public class ExceptionTest {

public static void main(String[] args) {

try{
int arr[]=new int[10];
arr[5]=20/0;
}
catch(ArithmeticException e)
{
System.out.println(“Arithmetic Exception”);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(“ArrayIndexOutOfBounds Exception”);
}
catch(Exception e)
{
System.out.println(“Exception occurs”+e.getMessage());
}
System.out.println(“res tof the code”);
}
}

Java Exception types :

There are three types of exceptions as defined by Oracle :

  1. Checked Exception
  2. Unchecked Exception
  3. Error
Checked Exception :

As name suggests, these exceptions are checked at compile time.Β The classes which are direct child classes of Throwable class except RuntimeException and Error are known as checked exceptions e.g. IOException, ClassNotFoundException, SQLException etc

Unchecked Exception:

These exceptions are not checked at compile time rather these are checked at run time.Β Β The classes which inherit RuntimeException are known as unchecked exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.

Error:

Condition which is irrecoverable is called as Error in Java e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.

Exception hierarchy:

All exception classes are sub-type of Throwable class. Thus Throwable is the top of exception hierarchy.

exceptionHandling

Java Exception propagation:

In case exception occurs in one method then developer should catch the exception in same method or should propagate the exception to its calling method then the exception should be caught in this method or should propagate to its calling method and so on until the exception is finally caught. The flow goes from top to down call stack. This is called exception propagation.

exceptionHandling1

Unchecked Exceptions are automatically propagated but the checked exceptions are not.

To propagate the checked exceptions, throws keyword is used. Exceptions , which should be propagated , needs to be declared using throws keyword in the respective method.

import java.io.IOException;

class Test{

void a()throws IOException{
throw new IOException(“device error”);//checked exception
}
void b()throws IOException{
a();
}
void c(){
try{
b();
}catch(Exception e){System.out.println(“exception handled”);}
}
public static void main(String args[]){
Test test=new Test();
test.c();
System.out.println(“normal flow…”);
}
}

Important Exception Handling Rules to remember :
  • Try block cannot be used alone. It should be followed with either catch, finally or both.
  • There can be multiple catch blocks for one try block. Each catch block can catch specific type of Exception. The sequence of catch block gets decided on the basis of exception defined in the block. The order of Catch block , in terms of exception, is most specific to most general i.e catch for ArithmeticException must come before catch for Exception.
  • Finally will always gets executed even if exception occurs in the code.
  • Checked exceptions are not automatically propagated, only unchecked exceptions are.
  • Exception Handling in case of Method Overriding :
    • If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception but it can declare unchecked exception.
    • If the superclass method declares an exception, subclass overridden method can declare same, subclass exception or no exception but cannot declare parent exception.

Custom Exceptions in Java :

Depending upon different scenarios,Β  Developer may need to throw own created exception which are often called as Custom exception/ user-defined exception.

Developer can decide the exception and its message as pe the need.

Below is the example to create own custom exception in Java :

classΒ InvalidAgeExceptionΒ extendsΒ Exception{

InvalidAgeException(StringΒ s){

super(s);

}Β Β }

Important differences :

Thanks for reading this article. I hope , you like it,

For any suggestions / feedback / question / clarification, Kindly post your comments in the below comment box.

Please subscribe our news letter and connect with social media accounts and don’t miss any articles.

Happy Reading!!!

Newsletter Updates

Enter your name and email address below to subscribe to our newsletter

Leave a Reply