Can we write any statements between try, catch and finally blocks in Java?


No, we cannot write any statements in between try, catch and finally blocks and these blocks form one unit.  The functionality of try keyword is to identify an exception object and catch that exception object and transfer the control along with the identified exception object to the catch block by suspending the execution of the try block. The functionality of the catch block is to receive the exception class object that has been sent by the try and catch that exception class object and assigns that exception class object to the reference of the corresponding exception class defined in the catch block. The finally blocks are the blocks which are going to get executed compulsorily irrespective of the exception.

We can write statements like try with catch block, try with multiple catch blocks, try with finally block and try with catch and finally blocks and cannot write any code or statements between these combinations. If we try to put any statements between these blocks, it will throw a compile-time error.

Syntax

try
{
   // Statements to be monitored for exceptions
}
// We can't keep any statements here
catch(Exception ex){
   // Catching the exceptions here
}
// We can't keep any statements here
finally{
   // finally block is optional and can only exist if try or try-catch block is there.
   // This block is always executed whether exception is occurred in the try block or not
   // and occurred exception is caught in the catch block or not.
   // finally block is not executed only for System.exit() and if any Error occurred.
}

Example

Live Demo

public class ExceptionHandlingTest {
   public static void main(String[] args) {
      System.out.println("We can keep any number of statements here");
      try {
         int i = 10/0; // This statement throws ArithmeticException
         System.out.println("This statement will not be executed");
      }
      //We can't keep statements here
      catch(ArithmeticException ex){
         System.out.println("This block is executed immediately after an exception is thrown");
      }
      //We can't keep statements here
      finally {
         System.out.println("This block is always executed");
      }
         System.out.println("We can keep any number of statements here");
   }
}

Output

We can keep any number of statements here
This block is executed immediately after an exception is thrown
This block is always executed
We can keep any number of statements here

Updated on: 06-Feb-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements