Java - Java Exceptions - Try...Catch

In Java, exceptions are the events that occur during the execution of a program, disrupting the normal flow of the program. Java provides built-in mechanisms to handle such exceptions in a program. This mechanism is called the try-catch block.

A try-catch block consists of two blocks: the try block and the catch block. The try block contains the code that is prone to throw an exception. The catch block is used to handle the exception if it is thrown.

try {
   // code that may throw an exception
}
catch (ExceptionType e) {
   // code to handle the exception
}

In the above syntax, the code in the try block is executed normally. If any exception occurs in the try block, the control is transferred to the catch block. In the catch block, we can define the code to handle the exception. The exception type can be specified in the catch block to handle a specific type of exception.

public class Example {
  public static void main(String[] args) {
    try {
      int a = 5 / 0; // Division by zero
    } catch (ArithmeticException e) {
      System.out.println("Exception: " + e.getMessage());
    }
    System.out.println("Program continues to execute...");
  }
}

In the above example, we have a try-catch block that tries to divide a number by zero, which results in an ArithmeticException. The catch block catches the exception and prints the error message. Finally, the program continues to execute.

Java also provides a finally block, which can be used to specify code that should be executed irrespective of whether an exception occurs or not.

public class Example {
  public static void main(String[] args) {
    try {
      int a = 5 / 0; // Division by zero
    } catch (ArithmeticException e) {
      System.out.println("Exception: " + e.getMessage());
    } finally {
      System.out.println("Finally block always executes...");
    }
  }
}

In the above example, we have added a finally block that will always be executed, irrespective of whether an exception occurs or not.

ArrayIndexOutOfBoundsException:

int[] arr = {1, 2, 3};
try {
   System.out.println(arr[3]);
} catch (ArrayIndexOutOfBoundsException e) {
   System.out.println("Error: Index out of bounds.");
}

NumberFormatException:

String str = "abc";
try {
   int num = Integer.parseInt(str);
} catch (NumberFormatException e) {
   System.out.println("Error: Cannot convert string to integer.");
}

NullPointerException:

String str = null;
try {
   System.out.println(str.length());
} catch (NullPointerException e) {
   System.out.println("Error: Object is null.");
}

ArithmeticException:

int num1 = 5;
int num2 = 0;
try {
   int result = num1 / num2;
} catch (ArithmeticException e) {
   System.out.println("Error: Cannot divide by zero.");
}

IOException:

try {
   FileInputStream file = new FileInputStream("filename.txt");
} catch (IOException e) {
   System.out.println("Error: File not found.");
}