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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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
{
    
                  // 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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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");
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
2
3
4
5
6
7
8
9
10
11
12
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
}
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
2
3
4
5
6
7
8
9
10
11
12
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");
}
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
2
3
4
5
6
7
8
9
int number;
 
String userInput = "one";
 
           // Assume we are capturing input from user dynamically
 
try {
          number = Integer.parseInt(userInput);
    } 
int number;

String userInput = "one";

           // Assume we are capturing input from user dynamically

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

Above statement is invalid

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

Above statement is invalid

1
2
3
finally {
              System.out.println("This block is always executed");
}
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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");
}
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

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