Nested try catch

Exception handlers can be nested within one another.

It means try, catch or a finally block can in turn contains another set of try catch finally sequence.

In such a scenario, when a particular catch or finally block is unable to handle an Exception, that exception will be rethrown automatically and such exception would be handled by the outer set of try catch handler.

Lets understand this with below use cases and example


Case 1 : Exception handling within try block


In this case, we will write try-catch block within a try block

This way we can modularize the exception handling to only required set of statements

If exception is thrown inside inner try block then it will try to find corresponding catch block within that block, if not found then exception will be thrown back to outer try block and will be handled by outer catch block

Consider below example

  1. package com.kb.Exception;
  2.  
  3. public class ExceptionHandlingTry {
  4.     public static void main(String[] args) {
  5.            try {
  6.                 System.out.println("Begin: Outer try block");
  7.                 try {
  8.                     System.out.println("Begin: Inner try block");
  9.                     int arr[] = {1,2,0};
  10.                     int res = 10 / arr[2];
  11.                     System.out.println(res);
  12.                 } catch (ArrayIndexOutOfBoundsException e) {
  13.                     System.out.println("ArrayIndexOutOfBoundsException caught");
  14.                 } finally {
  15.                     System.out.println("Inside Inner final");
  16.                 }
  17.             } catch (ArithmeticException e) {
  18.                 System.out.println("ArithmeticException caught");
  19.             } finally {
  20.                 System.out.println("Inside Outer finally");
  21.             }
  22.            System.out.println("Continue further lines .....");
  23.     }
  24.  
  25. }
package com.kb.Exception;

public class ExceptionHandlingTry {
	public static void main(String[] args) {
	       try {
	            System.out.println("Begin: Outer try block");
	            try {
	                System.out.println("Begin: Inner try block");
	                int arr[] = {1,2,0};
	                int res = 10 / arr[2];
	                System.out.println(res);
	            } catch (ArrayIndexOutOfBoundsException e) {
	                System.out.println("ArrayIndexOutOfBoundsException caught");
	            } finally {
	                System.out.println("Inside Inner final");
	            }
	        } catch (ArithmeticException e) {
	            System.out.println("ArithmeticException caught");
	        } finally {
	            System.out.println("Inside Outer finally");
	        }
	       System.out.println("Continue further lines .....");
	}

}


We can see that inside inner try block, code is throwing Arithmetic exception but there is no corresponding handler hence its throwing that exception to outer try and hence its handled by outer catch block.

Case 2 : Exception handling within catch block


In this case, we will write try-catch block within a catch block

Sometimes its required to handle the exception within a catch block if we write complex code in catch block.

Consider below example

  1. package com.kb.Exception;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.FileReader;
  5. import java.io.IOException;
  6.  
  7. public class ExceptionHandlingCatch {
  8.     public static void main(String[] args) {
  9.            try {
  10.                 System.out.println("Begin: Outer try block");
  11.                 int arr[] = {1,2,0};
  12.                 int res = 10 / arr[2];
  13.                 System.out.println(res);
  14.             } catch (ArithmeticException e) {
  15.                   try {
  16.                         System.out.println("Begin: Try within Catch block");
  17.                         readExceptionCodeAndPrintDetails(e.getMessage());
  18.                        
  19.                     } catch (IOException ex) {
  20.                         System.out.println("IOException caught");
  21.                     } finally {
  22.                         System.out.println("Inside Inner final");
  23.                     }
  24.             }
  25.            finally {
  26.                 System.out.println("Inside Outer finally");
  27.             }
  28.            System.out.println("Continue further lines .....");
  29.     }
  30.  
  31.     private static void readExceptionCodeAndPrintDetails(String details) throws IOException {
  32.         System.out.println("Code to read the exception code from File");
  33.         FileReader fileReader =
  34.                 new FileReader("exception.txt");
  35.  
  36.             BufferedReader bufferedReader =
  37.                 new BufferedReader(fileReader);
  38.  
  39.             String line ;
  40.             while(( line = bufferedReader.readLine()) != null) {
  41.                 System.out.println(line + "=> "+details);
  42.             }  
  43.  
  44.             bufferedReader.close();
  45.     }
  46.  
  47. }
package com.kb.Exception;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ExceptionHandlingCatch {
	public static void main(String[] args) {
	       try {
	            System.out.println("Begin: Outer try block");
	            int arr[] = {1,2,0};
                int res = 10 / arr[2];
                System.out.println(res);
	        } catch (ArithmeticException e) {
	        	  try {
		                System.out.println("Begin: Try within Catch block");
		                readExceptionCodeAndPrintDetails(e.getMessage());
		               
		            } catch (IOException ex) {
		                System.out.println("IOException caught");
		            } finally {
		                System.out.println("Inside Inner final");
		            }
	        } 
	       finally {
	            System.out.println("Inside Outer finally");
	        }
	       System.out.println("Continue further lines .....");
	}

	private static void readExceptionCodeAndPrintDetails(String details) throws IOException {
		System.out.println("Code to read the exception code from File");
		FileReader fileReader = 
                new FileReader("exception.txt");

            BufferedReader bufferedReader = 
                new BufferedReader(fileReader);

            String line ;
			while(( line = bufferedReader.readLine()) != null) {
                System.out.println(line + "=> "+details);
            }   

            bufferedReader.close(); 
	}

}


In the above program, we have added try catch exception handling within catch block

Catch block is performing file read operation and hence it may throw an IOException

In case, we are performing some operation within catch block which may throw an exception then its better to write Try-Catch within catch block to handle it

In above program, we are getting Arithmetic exception from outer Try block and its handled by outer Catch block but outer catch block is throwing IOException while reading file as File does not exist.

IOException is then handled by inner catch block.

Case 3 : Exception handling within finally block


In this case, we will write try-catch block within a Finally block

Sometimes its required to handle the exception within a finally block if we write complex code in finally block.

Consider below example

  1. package com.kb.Exception;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.FileReader;
  5. import java.io.IOException;
  6.  
  7. public class ExceptionHandlingFinally {
  8.     public static void main(String[] args) {
  9.         FileReader fileReader = null;
  10.         BufferedReader bufferedReader = null;
  11.         try {
  12.             System.out.println("Code to read the data from File");
  13.             fileReader = new FileReader("sample.txt");
  14.  
  15.             bufferedReader = new BufferedReader(fileReader);
  16.  
  17.             String line;
  18.             while ((line = bufferedReader.readLine()) != null) {
  19.                 System.out.println(line);
  20.             }
  21.  
  22.         } catch (IOException e) {
  23.             System.out.println("Inside Outer catch block");
  24.         } finally {
  25.             try {
  26.                 System.out.println("Begin: Finally block");
  27.                 bufferedReader.close();
  28.                 fileReader.close();
  29.  
  30.             } catch (Exception ex) {
  31.                 System.out.println("Exception caught while closing file");
  32.             }
  33.         }
  34.         System.out.println("Continue further lines .....");
  35.     }
  36.  
  37. }
package com.kb.Exception;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ExceptionHandlingFinally {
	public static void main(String[] args) {
		FileReader fileReader = null;
		BufferedReader bufferedReader = null;
		try {
			System.out.println("Code to read the data from File");
			fileReader = new FileReader("sample.txt");

			bufferedReader = new BufferedReader(fileReader);

			String line;
			while ((line = bufferedReader.readLine()) != null) {
				System.out.println(line);
			}

		} catch (IOException e) {
			System.out.println("Inside Outer catch block");
		} finally {
			try {
				System.out.println("Begin: Finally block");
				bufferedReader.close();
				fileReader.close();

			} catch (Exception ex) {
				System.out.println("Exception caught while closing file");
			}
		}
		System.out.println("Continue further lines .....");
	}

}


In the above program,We have written exception handling code in finally block as well

In try block, we are trying to read the content of a file

In finally, we are trying to close the file but bufferedReader points to null , it will throw an exception while closing a file and that is caught in the catch block within the finally block. So its required to handle exceptions within finally as well.

Note :
Its not good to use nested try-catch unless there is a necessity of doing so.

About the Author

Karibasappa G C (KB)
Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on