Exception handling in Java - the advance concepts


Using multiple catch block, nesting of try catch block and creating custom Exception handler, this article will teach you advance Exception handling in java.

Advance Exception Handling Concepts

The basics of Exception handling has been already explained in this post. if you are new You must first follow this first and than come back to this post.

Exception Handling Basics

After basics I am going to explain the advance exception handling which includes nesting and multiple catch block. throws and throw concept and Custom Exception handling. So if you are good with the basics proceed or else go through the basics first.

Let me start with the throws, the throws is used to tell the JVM that some particular type of exceptions could occur in the program, and you are free from putting try/catch every here and there in the program. But the problem is that now the JVM will handle the exception at its own level. The use of throws is usually to prevent the caller method from being effected by the method which may cause an exception. for example in following program the method div may throw an ArithmeticException. But the method does not includes the try catch so we can use the throws followed by the Exception type to warn the caller method(main in this case) to take care of the exception handling.


public class ExceptionDemo {
    
    static void div(int n, int d) throws ArithmeticException{
        System.out.println(n/d);
    }
    
    public static void main(String[] args) {
        int[] a = new int[5];
        try{
            div(100,0);
        }
        catch(Exception e){
            System.out.println(e);
        }
    }
}

When you run this program this will call the div method which in turns generate an exception but as we have put the caller function in try catch and the div tells by the virtue of throws that there could be AirthmeticException this will be handled properly.

The same can be obtain with the throw statement but this is put after the statement after the statement which may generate the exception. As you can see in this program, however it would serve the same.


public class ExceptionDemo {
    
    static void div(int n, int d) {
        System.out.println(n/d);
        throw new ArithmeticException();
    }
    
    public static void main(String[] args) {
        int[] a = new int[5];
        try{
            div(100,0);
        }
        catch(Exception e){
            System.out.println(e);
        }
    }
}

This is simple to understand, there is more to the concept of exception you can use the nested try catch block without any trouble.


class ExceptionDemo{
	public static void main(String[] args){
		try{
			try{
				System.out.println(1/0);
			}
			catch(ArithmeticException ae){
				System.out.println("Inner block"+ae);
			}
		}
		catch(Exception e){
			System.out.println("outer block:"+e);
		}
	}
}

in this program output is as follows:

Inner blockjava.lang.ArithmeticException: / by zero

and in another version of this program


public class ExceptionDemo {
   public static void main(String[] args) {
        try{
        	int[] a = new int[2];
		try{
			System.out.println(a[5]);
		}
		catch(ArithmeticException ae){
			System.out.println("inner block"+ae);
		}
	}
	catch(Exception e){
		System.out.println("outer block:"+e);
	}
    }
}

now the output changes to

outer block:java.lang.ArrayIndexOutOfBoundsException: 5

So you see this is how you work the nested blocks of try catch. if the exception is thrown in some block it will look for the nearest matching catch block to handle the exception.

Multiple catch blocks

Similarly you can use multiple catch block for one try block, in this case too the JVM will look for the nearest catch block matching the exception type.


public class ExceptionDemo {
   public static void main(String[] args) {
        int[] a = new int[2];
        try{
            System.out.println(a[5]);
	}
	catch(ArithmeticException ae){
            System.out.println("inner block"+ae);
	}
	catch(Exception e){
            System.out.println("outer block:"+e);
        }
    }
}

the output will remain same as for earlier program

outer block:java.lang.ArrayIndexOutOfBoundsException: 5

Custom Exception Handling

and now finally let me explain the custom exception handling. As I told earlier in the article that Exception is super class for the general hierarchy for the Exception handling classes. So we shall extend this into our custom class and define the exception behavior in that class.


public class ExceptionDemo {
   public static void main(String[] args){
        try{
            throw new CustomException();
        }
        catch(CustomException e){
            System.out.println(e);
        }
    }
}

class CustomException extends Exception{
    public String toString(){
        return "This is a custom Exception";
    }
}

First you need to define any custom functionality or handling method which would occur on exception occurrence and a statement which will throw an exception. Rest JVM will manage. the output of above program is

This is a custom Exception

This is how Exception handling works in Java. If there is any query in your mind please post it in comments or in out contact us section.

Note: there are several types of exception classes in Java but you'll possibly underway most common ones unless you are a Java dreamer. There most common ones are
ArrayIndexOutOfBound
NullPointerException
FileNotFoundException
NumberFormatException
ArithmeticException
IlligalAccessException
ClassNotFoundException

there are lot more to it but you will have to check on official Java documents if you want to know them all.