Try-Catch-Finally Java Example Program

Try block:

  • Try block has the main code, which code may throw an exception. 

a try block syntax looks like the following:

try {
    //main code
}

Catch block:

  • The catch block contains exception code that is executed when thrown by the Try Block.
  • Possible to declare one or more catch block for different type of exception
  • No code can be between try block and the first catch block.
  • Catch blocks declare directly after the try block. 

a catch block syntax looks like the following:

try {

} catch (ExceptionType1 name) {
    //exception code
} catch (ExceptionType2 name) {
    //exception code
}

Finally, block:

  • The finally block always executes after try block or catch block.
  • finally block is a block that is used to execute clean up code such as streaming or closing connection,  etc.
  • Declare cleanup code in a finally block is always a best practice in Java, even when no exceptions have occurred.

a finally block syntax looks like the following:

try {

} catch (ExceptionType1 name) {
    //exception code
} catch (ExceptionType2 name) {
    //exception code
}
finally {
    if (out != null) { 
        // Close Out - Clean Up Code
    } else { 
        // No need to close Out
    } 
} 

General Syntax

try{
	//Do Something
}catch(Exception e){
	//Do something with caught exception
}finally{
	//Do something always - even when there is an exception
}


Try-Catch-Finally Example Program

public class TryCatchFinally {
    static void splitString(String text){
        try{  
            String[] splittedString =text.split("/");  
            for(int i = 0; i < splittedString.length; i++){
                System.out.println("Splitted string array of index "+i+" is : "+splittedString[i]);
            }
        }  
        catch(Exception e){
            System.out.println("Exception while performing division : "+e.toString());
        }  
        finally{
            System.out.println("I am inside finally block");
        }  
    }
    
    public static void main(String args[]){
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter number 1 : ");
        String text = scanner.nextLine();
        if(text.length()>0){
            splitString(text);
        }else{
            //Passing null as input for splitting
            splitString(null);
        }
    }
}


Sample Output 1

Enter the input text :  

Exception while performing division : java.lang.NullPointerException
I am inside finally block


Sample Output 2 

Enter the input text :  
tea/cup
Splitted string array of index 0 is : tea
Splitted string array of index 1 is : cup
I am inside finally block