Example & Tutorial understanding programming in easy ways.

What are the possible combination to write try, catch finally block?

While you were writing an efficient source code then It should be noted that all exceptions that can be generated are subclasses of the class. java.lang.throwable.Exception.

With this in mind and the idea of a hierarchy of errors, it is possible to write effective and working exception Try, Catch and Finally blocks.

When adding the exceptions, the order in which they appear MUST be in an upward order. What this means is that you work from lower subclasses towards the superclass Exception.

If theses exceptions are written in the opposite order, then the lower catch blocks are useless since a superclass will catch exceptions found in its subclasses.

The correct way to do the above is as follows
:

try{}
catch(IOException e){}
catch(Exception e){}

Now all the  IO exceptions will be caught by the first catch block and all other exceptions and get handled securely by the super class Exception.

Following program illustrates the usage of finally block.

public class FinallyBlock   
{
    public static void main(String args[])  
    {
          int marks[ ] = { 76, 57, 83, 46, 38 };
          System.out.println("OK 1");
 
          try  
          {
                System.out.println(marks[10]);
          }
          catch(ArithmeticException e)  
          {
                System.out.println("Some problem: " + e);
          }
          finally  
          {
                 System.out.println("OK 2");
          }
          System.out.println("OK 3");
    }    
}

Read More →