Exception Handling in Java With Example

In this post, we will see Exception Handling in Java With Example.

Exception Handling in Java With Example

Exception in java.

An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program’s executions.

Checked and Unchecked Exception in java.

Checked Exception.

All Exceptions which are not a subclass of RuntimeException are called Checked Exception. We need to handle Checked exception at compile time by using throws keywords or by using try-catch block

Let’s see a couple of Examples of Checked Exception.

IOException
FileNotFoundException
ClassNotFoundException
CloneNotSupportedException
NoSuchMethodException
InterruptedException
NoSuchFieldException
ParseException

Example of Checked exception.

import java.io.*;
class Exception1 { 
public static void main(String args[]) {
    FileInputStream fis = new FileInputStream("d:/rakesh"); 
    fis.close();
  }
}

The above code will not compile because there is a constructor defined public FileInputStream(String name) throws FileNotFoundException which is checked exception and also close() method throws IOException which is also a checked exception. We need to do following changes in order to resolve the compilation error.

First Solution – As we know checked exception must be handle at compile time either by using throws keyword or by using a try-catch block. So here firstly we are using throws keyword.

import java.io.*;
class Exception1 { 
public static void main(String args[]) throws Exception {
    FileInputStream fis = new FileInputStream("d:/rakesh"); 
    fis.close();
  }
}

Second Solution –  Here we are going to use the try-catch block.

import java.io.*;
class Exception1 { 
public static void main(String args[]) {
try {
    FileInputStream fis = new FileInputStream("d:/rakesh"); 
    fis.close();
}catch (Exception e) {
    e.printStackTrace();
    }
  }
}

Unchecked Exception.

All Exceptions which are the subclass of RuntimeException is called unchecked exceptions. Like Checked exceptions, it is not mandatory to handle RuntimeExcepton by using throws keyword or try-catch block. If we do some programming mistakes then JVM will automatically throw a runtime exception. It will always happen at runtime.

Example of UnChecked Exception.

NullPointerException
ClassCastException
ArrayIndexOutOfBoundsException
IllegalStateException
NumberFormatException
IllegalArgumentException
IllegalMonitorStateException
IndexOutOfBoundsException

Let’s see an example that throws NullPointerException.

class NullPointerExample{ 
    public static void main(String args[]) {
    String s=null;
    System.out.println(s.hashCode());
  }
}

Here this code will not give any compile-time error, it will throw NullPointerException when you will try to execute.

Difference between checked and unchecked exception in java.

Let’s see the difference between checked and unchecked exception –

Checked ExceptionUnChecked Exception
1.All Exception which is not subclass of RuntimeException is Checked Exception. 2.it happens at runtime.
3.In case of Checked Exception you must need to handle at compile time either by using try catch or throws keyword.3.it is not mandatory to handle unchecked exception.
4.Example is :-FileNotFoundException.4.Example is :-NullPointerException

Exception in case of method overriding.

when the superclass method throws some exception.

Subclass overridden method can declare subclass exception or same exception(i.e declares in superclass) or no exception.

Example when declares subclass exception.

import java.io.FileNotFoundException;
import java.io.IOException;
class Animal {
    public void m1() throws IOException{
    System.out.println("super class method");
  }
}
class Tiger extends Animal{
    // subclass exception
    public void m1() throws FileNotFoundException{
    System.out.println("sub class method");
  }
}
public class Test4 {
    public static void main(String[] args) throws Exception{
    Animal a=new Tiger();
    a.m1();
  }
}

Example when the overridden method declares the same exception.

import java.io.IOException;
class Animal {
    public void m1() throws IOException{
    System.out.println("super class method");
  }
}
class Tiger extends Animal{
    // same exception
    public void m1() throws IOException{
    System.out.println("sub class method");
  }
}
public class Test4 {
public static void main(String[] args) throws Exception{
Animal a=new Tiger();
a.m1();
}
}

Example when the overridden method declares no exception.

import java.io.IOException;
class Animal {
public void m1() throws IOException{
    System.out.println("super class method");
  }
}
class Tiger extends Animal{
    // no exception
    public void m1() {
    System.out.println("sub class method");
  }
}
public class Test4 {
    public static void main(String[] args) throws Exception{
    Animal a=new Tiger();
    a.m1();
  }
}

when the superclass method doesn’t throw an exception.

Subclass overridden method can declares only RuntimeException or unchecked exception not Checked exception.

Understanding Try Catch and finally block.

The catch block will execute only in case if we have some exception in the try block. The finally block will get always executed.

Example 1.

public class Example1 {
public static void main(String[] args) {
	try{
		
		//some exception
		
	}catch(Exception e){
		// if some exception will come inside try block 
		//then only catch block will execute
		
	}finally {
		//it will execute always even exception comes inside try block or not
	}
}
}

Example 2 – Try block is throwing an exception. In this case catch and finally block will execute.

package exception;

public class Example1 {
public static void main(String[] args) {
	try{		
		String s1 = null;		
		//below line will throw NullpointerException, catch block will execute.
		System.out.println(s1.toString());		
	}catch(Exception e){		
		System.out.println("catch block  "+e);		
	}finally {
		System.out.println("finally block");		
	}
}
}

Output is –

catch block java.lang.NullPointerException
finally block

Example 3 – Try block is not throwing an exception.

package exception;

public class Example1 {
public static void main(String[] args) {
	try{		
		String s1 = "ram";
		System.out.println("value of s1 "+s1);
		
	}catch(Exception e){		
		System.out.println("catch block  "+e);		
	}finally {
		System.out.println("finally block");		
	}
}
}

Output is –

value of s1 ram
finally block

Possible combinations of try, catch, and finally block.

Note – try block must come with catch block or finally block. We can’t write only try block.

Example 1 – We can write try with finally.

public class Example1 {
public static void main(String[] args) {
	try{		
		String s1 = "ram";
		System.out.println("value of s1 "+s1);		
	}finally {
		System.out.println("finally block");		
	}
}
}

Output is –

value of s1 ram
finally block

Example 2 – We can write try with the catch.

public class Example1 {
public static void main(String[] args) {
	try{		
		String s1 = null;
		System.out.println("value of s1 "+s1.length());		
	}catch(Exception e) {
		System.out.println(e);
	}
}
}

Output is – java.lang.NullPointerException

Example 3 – We can write try with multiple catches.

package exception;

public class Example1 {
public static void main(String[] args) {
	try{		
		String s1 = null;
		System.out.println("value of s1 "+s1.length());
		
	}catch(NullPointerException e) {
		System.out.println(e);
	}catch(Exception e) {
		System.out.println(e);
	}
}
}

Output is – java.lang.NullPointerException

Example 4 – We can write try block within the try block.

package exception;

public class Example1 {
public static void main(String[] args) {
	try{
		
		String s1 = "ram";
		System.out.println("length of s1 "+s1.length());		
		try {
			System.out.println("try inside try");
		}catch(Exception e){
			
		}
		
	}catch(NullPointerException e) {
		System.out.println(e);
	}catch(Exception e) {
		System.out.println(e);
	}
}
}

Output is –

length of s1 3
try inside try

Example 5 – We can write try block within the catch block or finally block.

package exception;

public class Example1 {
public static void main(String[] args) {
	try{		
		String s1 = null;
		System.out.println("length of s1 "+s1.length());				
	}catch(NullPointerException e) {
		try {
			System.out.println("try inside catch block");
		}catch(Exception e1){
			
		}
	}finally {
		try {
			System.out.println("try inside finally block");
		}catch(Exception e1){
			
		}
	}
}
}

Output is –

try inside catch block
try inside finally block

Note – Finally block mainly used to perform resource clean up or session closing or database connection closing task.

Interview talk – You may be asked in an interview when finally block will not execute. We can use System.exit(0) if we don’t execute finally block. Again you may asked what will happen if we write reurn statement inside try block, finally block will get executed or not. The answer is yes, still finally block will execute.

Let’s see an example where we will see how to stop finally block to execute. If we call System.exit(0) in the try block finally block will not execute.

Example 1 – Writing System.exit(0) inside try block.

package exception;

public class Example1 {
public static void main(String[] args) {
	try{
		System.out.println("before system.exit()");
		System.exit(0);
		System.out.println("after system.exit()");		
	}catch(NullPointerException e) {
		System.out.println("catch block");
	}finally {
		System.out.println("finally block will not execute, we have called System.exit(0)");
	}
}
}

Output is – before system.exit()

In the above example, we can see as soon as System.exit(0) has been called our program terminated, the finally block didn’t execute. Let’s see what happens when we write return inside try block.

Example 2 –

package exception;

public class Example1 {
public static void main(String[] args) {
	try{		
		return;		
	}catch(NullPointerException e) {
		System.out.println("catch block");
	}finally {
		System.out.println("finally block will execute, even we have return statement inside try block");
	}	
	System.out.println("hello");
}
}

The output is – finally block will execute, even we have return statement inside try block

Even after writing the return statements, the finally block is executing. Did you notice we don’t have hello in output?

Creating a custom exception in Java With Example.

In this section, we will see how to create custom exception in java and what is the use of them.

When we create our own exception by extending Exception class or RuntimeException class, it is called a custom exception.

The custom exception is mainly used to show custom messages.

Steps to define custom exception.

  1. Define CustomException class(generally it should be your application name) extending Exception or  RuntimeException class.
  2. Define one and two parametrized constructor.
  3. In each constructor, we need to define super.
  4. Use throw keyword to show the proper exception message.

Creating a custom exception extending Exception class.

package customexception;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class CustomException extends Exception{
	
	 public CustomException(String message) {
	        super(message);
	    }

	    public CustomException(String message, Throwable t) {
	        super(message, t);
	    }
public static void main(String[] args) {
		try {
			String bookId = null;
	        if(bookId == null) {
	        	throw new CustomException("book id can't be null");
	        }
	    
		}catch(Exception e) {
			e.printStackTrace();
		}
		
		 
		
		
		
}
}

Output is –

customexception.CustomException: book id can’t be null
at customexception.CustomException.main(CustomException.java:20)

Creating a custom exception extending RuntimeException class.

Let’s create Custom exception extending RuntimeException.

package customexception;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.util.Date;

public class CustomException1 extends RuntimeException{
	 public CustomException1(String message) {
	        super(message);
	    }
	 public CustomException1(String message, Throwable t) {
	        super(message, t);
	 }
	 
	 
	public static void main(String[] args) {		
		String dateAsString = "11101988";		
		DateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");		
		try {
			Date date = dateFormat.parse(dateAsString);
		}catch(Exception e) {
			throw new CustomException1("problem in parsing the date");
		}							
	}
}

Output is –

Exception in thread “main” customexception.CustomException1: problem in parsing the date
at customexception.CustomException1.main(CustomException1.java:27)

We can make the exception message more understandable, using two parametrized constructor.

public CustomException(String message, Throwable t) {
	        super(message, t);
	    }

Example.

package customexception;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.util.Date;

public class CustomException1 extends RuntimeException{
	 public CustomException1(String message) {
	        super(message);
	    }

	 public CustomException1(String message, Throwable t) {
	        super(message, t);
	 }
	 	 
	public static void main(String[] args) {
		
		String dateAsString = "11101988";		
		DateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");		
		try {
			Date date = dateFormat.parse(dateAsString);
		}catch(Exception e) {
			throw new CustomException1("problem in parsing the date",e);
		}							
	}

}

Output is –

Exception in thread “main” customexception.CustomException1: problem in parsing the date
at customexception.CustomException1.main(CustomException1.java:27)
Caused by: java.text.ParseException: Unparseable date: “11101988”
at java.text.DateFormat.parse(Unknown Source)
at customexception.CustomException1.main(CustomException1.java:25)

Obserb the output of both example. We have more specific message now.

So now the question arises what is the difference between extending Exception class and RuntimeException. While extending the Exception class it will create checked exception whereas If we extend RuntimeException it will be created an Unchecked exception.

Try with multiple catch blocks in java with example.

In this section, we are going to see.

  • How to implement try with multiple catch blocks in java.
  • What is the benefit of multiple catch blocks? How to implement in the real-time scenario?

Let’s see an example.

package exceptioncatchmultipleexceptio;

public class Test {
public static void main(String[] args) {
	try {
		//some code
		
	}catch(NullPointerException n) {
		System.out.println(n);
	}catch(RuntimeException r) {
		System.out.println(r);
	}catch(Exception e) {
		System.out.println(e);
	}
}
}

The above example is a valid implementation of using multiple catch block. In try block suppose we have logic which may cause NullPointerException or any other RuntimeExcetion, if we will have NullPointerException line 10 will execute, if we have some other runtrime exception types(eg-  ClassCastException) then line 12 will execute else line 14 will execute.

Let’s modify the code something like below.

package exceptioncatchmultipleexceptio;

public class Test {
public static void main(String[] args) {
	try {
		//some code
		
	}catch(Exception n) {
		System.out.println(n);
	}catch(RuntimeException r) {
		System.out.println(r);
	}catch(NullPointerException e) {
		System.out.println(e);
	}
}
}

This one will give a compilation error.

While defining catch block we need to take care, child exception should come first. As we can see in the above example we have defined NullPointerException first then RuntimeException and then Exception. What will happen if we change the sequence of exception inside the catch block? It will give a compilation error. Why? When we use Exception at first palace, it will take care of all types of exception. We no need to define NullPointerException or any child exception of the Exception class.

Again the question arises if we can handle all kind of exception with Exception class why we need multiple catch block. We can use only one catch block with the Exception class. One possible reason – It helps to show the specific exception message. Suppose we have a scenario where bookName can’t be null if empId is null then throw some exception. The general approach will be we will define a custom exception and check if empId is null throw some user defined message i.e bookName can’t be null. Let’s see an example.

We are going to define a custom exception and will use with catch block.

package customexception;
 
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
 
public class CustomException extends Exception{		 
	    public CustomException(String message, Throwable t) {
	        super(message, t);
	    }
public static void main(String[] args) {
		try {
			String bookId = null;
	        if(bookId == null) {
	        	throw new CustomException("book id can't be null");
	        }	    
		}catch(Exception e) {
			e.printStackTrace();
		}				 						
}
}

Let’s see how to use this CustomException in catch block.

package exceptioncatchmultipleexceptio;

 class BookException extends RuntimeException{
	
	    public BookException(String message) {
	        super(message);
	    }	    	    
} 

public class Test {
public static void main(String[] args) {
	try {		
		//some code which may throw NullPointerException
		//some code which may throw other type of exception
		String bookName = null;
		if(bookName == null) {
			throw new BookException("book name can't be null");
		} 
		    	        		
	}catch(BookException n) {
		System.out.println(n);
	}catch(NullPointerException r) {
		System.out.println(r);
	}catch(Exception e) {
		System.out.println(e);
	}
}
}

Output is –

exceptioncatchmultipleexceptio.BookException: book name can’t be null

In the above example, we have code that may throw NullPointerException or Any other exception or BookException.

Return statement in exception handling in Java with Example.

Here we will see what will happen if we write return statement inside the try, catch or finally block.

Let’s see some examples.

Example 1.

package exception;

public class Example1 {
public static void main(String[] args) {
	try{		
		return;
		
	}catch(NullPointerException e) {
		System.out.println("catch block");
	}
	
}
}

Will the above code compile? Yes, it will compile successfully, after running it will return nothing.

Example 2 –

package exception;

public class Example1 {
public static void main(String[] args) {
	try{		
		return;
		
	}catch(NullPointerException e) {
		return;
	}finally {
		return;
	}		
}
}

The above code will compile successfully.

Example 3 –

package exception;

public class Example1 {
public static void main(String[] args) {
	try{		
		return;
		
	}catch(NullPointerException e) {
		System.out.println("catch block");
	}finally {
		System.out.println("finally block");
	}			
}
}

Output is – finally block

The finally block will execute even we have a return statement inside try block. It will not execute only when we will call System.exit() before execution of finally block.

Example 4 –

package exception;

public class Example1 {
public static void main(String[] args) {
	try{		
		System.exit(0);
		
	}catch(NullPointerException e) {
		System.out.println("catch block");
	}finally {
		System.out.println("finally block");
	}	
  }
}

When you will run the above program it will print nothing.

Example 5 –

package exception;

public class Example1 {
public static void main(String[] args) {
	try{		
		return;
		
	}catch(NullPointerException e) {
		System.out.println("catch block");
	}finally {
		System.out.println("finally block");
	}	
	System.out.println("hello");
  }
}

Output is – finally block.

Example 6 –

package exception;

public class Example1 {
public static void main(String[] args) {
	try{		
		return;
		
	}catch(NullPointerException e) {
		return;
	}finally {
		System.out.println("finally block");
	}
	
	System.out.println("hello");
  }
}

The above code will give a compilation error. Unreachable code.

That’s all about Exception Handling in Java With Example.

You may like.

Hibernate tutorial.

Summary – we have seen Exception Handling in Java With Example.