try-catch-finally in Java

try, catch and finally keywords are used to handle the exceptions in java

The structure of this is as follows:

  1. try
  2. {
  3.    
  4.                   // code that may throw exceptions
  5.  
  6. }
  7.          //You can't keep statements here
  8.  
  9.  catch (Exception e)
  10.  
  11. {
  12.                          // code to handle the exception thrown in try block
  13.                           // If exception is not thrown, then this block will not be executed
  14. }
  15.  
  16.  //You can't keep statements here
  17.  
  18. finally
  19. {
  20.                          // Finally block, where code always gets executed, regardless of exception thrown or not , handled or not.
  21.                           // Generally code related to clean up resources is kept here
  22. }
  23.  
  24.                        //You can keep any number of statements here
try
{
    
                  // code that may throw exceptions

}
         //You can't keep statements here

 catch (Exception e) 

{
                         // code to handle the exception thrown in try block
                          // If exception is not thrown, then this block will not be executed
} 

 //You can't keep statements here

finally 
{
                         // Finally block, where code always gets executed, regardless of exception thrown or not , handled or not.
                          // Generally code related to clean up resources is kept here
}

                       //You can keep any number of statements here


try block : In try block, keep those statements which may throw exceptions during run time.

catch block : This block handles the exceptions thrown by try block. It takes one argument of type java.lang.Exception or any sub type of java.lang.Exception.

finally block : Whether exception is thrown or not and thrown exception is handled or not, this block will be always executed.

Example 1:

The following code catch an exception may be thrown when dividing number by zero

  1. int numerator=10;
  2.  
  3. int denominator=0;
  4.  
  5. int result=0;
  6.  
  7. try
  8. {
  9.  
  10.                System.out.println("Try-begin");
  11.  
  12.                result = numerator/denominator;
  13.  
  14.                System.out.println("This statement will not be executed as exception is thrown in above line");
  15.  
  16. }
  17.      //You can't keep statements here
  18.  
  19.  catch (ArithmeticException ex)
  20.  
  21. {
  22.    
  23.                System.out.println("The thrown ArithmeticException will be handled here");
  24.  
  25. }
  26.     //You can't keep statements here
  27.  
  28. finally
  29. {
  30.  
  31.                System.out.println("This block is always executed");
  32.  
  33. }
  34.  System.out.println("Program continues further execution from here");
int numerator=10;

int denominator=0;

int result=0;

try 
{

               System.out.println("Try-begin");

               result = numerator/denominator;

               System.out.println("This statement will not be executed as exception is thrown in above line");

}
     //You can't keep statements here

 catch (ArithmeticException ex) 

{
   
               System.out.println("The thrown ArithmeticException will be handled here");

}
    //You can't keep statements here

finally
{

               System.out.println("This block is always executed");

}
 System.out.println("Program continues further execution from here");


Rules

1. We can have try block with only catch block without finally block

2. We can have try block with only finally block without catch block

3. We can’t have only try block or catch block or finally block alone.

In simple words, Try block in java should be followed by either catch block or finally block or both the blocks.


Example for Rule 1

  1. int number;
  2.  
  3. String userInput = "one";
  4.  
  5.     // Assume we are capturing input from user dynamically
  6. try {
  7.  
  8.                  number = Integer.parseInt(userInput);
  9.  
  10. } catch (NumberFormatException ex) {
  11.  
  12.                  number = -1;    // assigning a default value as -1 to handle the invalid string format for number
  13. }
int number;

String userInput = "one";

    // Assume we are capturing input from user dynamically
try {

                 number = Integer.parseInt(userInput);

} catch (NumberFormatException ex) {

                 number = -1;    // assigning a default value as -1 to handle the invalid string format for number
}


Example for Rule 2

  1. int number;
  2.  
  3. String userInput = "one";
  4.  
  5.         // Assume we are capturing input from user dynamically
  6. try {
  7.  
  8.               number = Integer.parseInt(userInput);
  9.  
  10. } finally {
  11.  
  12.              System.out.println("This block is always executed");
  13. }
int number;

String userInput = "one";

        // Assume we are capturing input from user dynamically
try {

              number = Integer.parseInt(userInput);

} finally {

             System.out.println("This block is always executed");
}


Example for Rule 3

  1. int number;
  2.  
  3. String userInput = "one";
  4.  
  5.            // Assume we are capturing input from user dynamically
  6.  
  7. try {
  8.           number = Integer.parseInt(userInput);
  9.     }
int number;

String userInput = "one";

           // Assume we are capturing input from user dynamically

try {
          number = Integer.parseInt(userInput);
    } 

Above statement is invalid

  1. catch (NumberFormatException ex) {
  2.               number = -1;    // assigning a default value as -1 to handle the invalid string format for number
  3. }
catch (NumberFormatException ex) {
              number = -1;    // assigning a default value as -1 to handle the invalid string format for number
}

Above statement is invalid

  1. finally {
  2.               System.out.println("This block is always executed");
  3. }
finally {
              System.out.println("This block is always executed");
}

Above statement is invalid

All the above statement written independently are invalid.


When finally block will not be executed ?


One exception for finally block is, if there is a System.exit(); is written either in the try or catch block, the finally block won’t be executed.

For example, in the following code, the finally block won’t be executed as System.exit(0); is written in the catch block.

  1. int number;
  2.  
  3. String userInput = "one";
  4.  
  5. try {
  6.  
  7.                 number = Integer.parseInt(userInput);
  8.  
  9. } catch (NumberFormatException ex) {
  10.  
  11.                number =-1;
  12.  
  13.                System.exit(0);
  14.  
  15. } finally {
  16.  
  17.                System.out.println("This block is not executed as System.exit(0) is written in catch block");
  18. }
int number;

String userInput = "one";

try {

                number = Integer.parseInt(userInput);

} catch (NumberFormatException ex) {

               number =-1;

               System.exit(0);

} finally {

               System.out.println("This block is not executed as System.exit(0) is written in catch block");
}

About the Author

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