Try - Catch


Try - Catch

The main code is written inside a TRY block. The exception handling code is written in the CATCH block. FINALLY is an optional code block which is always executed even if an exception occurs or not.

Syntax:

try {
//statements
// code block where exceptions can be raised
}
catch (Exception1 name) {
// statements for exception handling for Exception1 }
catch (Exception2 name) {
// statements for exception handling exception handler for Exception2
}
// optional
finally {
// code block which is to be executed after try block ends
}


Note: We can have multiple catch blocks in a block of code.

Example :

Com.knowledge2life public class Main { public static void main(String[] args) { try { int[] myNumbers = {1, 2, 3}; System.out.println(myNumbers[10]); } catch (Exception e) { System.out.println("Knowledge2life"); } }}

OUTPUT:

Knowledge2life