Choose Your Language

Thursday 4 April 2013

Try Catch Finally Scenario's

try catch finally block
Syntax:
 try{
        statements;
    }catch (Exception e) {
        // TODO: handle exception
    }finally{
        statements;
    }

Example:
public class TryCatchFinally {
void display(){
    try{
        statements;
    }catch (Exception e) {
        // TODO: handle exception
    }finally{
        statements;
    }
}
}

Scenario's
1. try catch finally inside try block
Example:
public class TryCatchFinally {
void display(){
    try{
        try{
              statements;
             }catch (Exception e) {
                 // TODO: handle exception
             }finally{
                    statements;
             }

         }catch (Exception e) {
        // TODO: handle exception
         }finally{
        statements;
         }
  }
}

2. try catch inside catch block
Example:
try{
        statements;
    }catch (Exception e) {
     try{
        statements;
          }catch (Exception e) {
        // TODO: handle exception
          }

        // TODO: handle exception
    }finally{
        statements;
    }

 3. try catch inside finally block
Example:
public class TryCatchFinally {
void display(){
    try{
        statements;
    }catch (Exception e) {
        // TODO: handle exception
    }finally{
        try{
          statements; 
        }catch (Exception e) {
            // TODO: handle exception
        }  
 
    }
}
}

4. try and finally without catch block
Example:
public class TryCatchFinally {
void display(){
    try{
          statements;
    }finally{
          statements; 
    }
}
}

5. try and multiple catch block
Example:
public class TryCatchFinally {
void display(){
    try{
        statements;
    }catch (NullPointerException e) {
        // TODO: handle exception
    }catch (Exception e) {
        // TODO: handle exception
    }
finally{
         statements;  
    }   
}
}

No comments:

Post a Comment