The catch keyword is used in a try-catch block. A catch block is always comes after a try block, if any exception occurs inside try block, then it is handled by the corresponding catch block. The purpose of catch block is to provide a meaningful error message.
try{ //statements }catch(Exception e){ //exception handling statements }
Example of catch keyword
If exception occurs: When a number is divided by zero, it raises an ArithmeticException. If the code that raises exception is placed inside a try block, then the raised exception is handled by the corresponding catch block.
public class JavaExample { public static void main(String[] args) { try{ int num1 = 100, num2 =0; int quotient = num1/num2; System.out.println(quotient); }catch(ArithmeticException e){ System.out.println("Cannot divide a number by zero"); } } }
Output:
Cannot divide a number by zero
If exception doesn’t occur: If an exception doesn’t occur inside try block then the catch block doesn’t execute and the program would run as it would without try-catch blocks.
public class JavaExample { public static void main(String[] args) { try{ int num1 = 100, num2 =10; int quotient = num1/num2; System.out.println(quotient); }catch(ArithmeticException e){ System.out.println("Cannot divide a number by zero"); } } }
Output:
10
Example 2: Multiple catch blocks
public class JavaExample { public static void main(String[] args) { try{ int[] arr = {2, 4, 6, 8, 10}; //arr valid indexes are from 0 till 4 System.out.println(arr[9]); }catch(ArithmeticException e){ System.out.println("Cannot divide a number by zero"); }catch(ArrayIndexOutOfBoundsException e){ System.out.println("Access array elements within limits"); }catch(Exception e){ //This is a generic exception handler, if the exception is //not caught by previous catch blocks, then it would be //handled here, All exception classes comes under Exception class System.out.println("There is an issue with the code inside try"); } } }
Output:
Access array elements within limits
Points to Note:
- A try block can have multiple catch blocks.
- A catch block cannot exist without a try block.
- If exception doesn’t occur then catch doesn’t execute.