40. How is exception handling done in Java?

How is exception handling done in Java?

  • Try catch block is used for exception handling. If you think a block code can throw an exception, you can surround them with a try block, and catch block will catch them and handle exception. Therefore, the normal follow of program will be maintained

Example 

 

public class ExceptionHandlingExample {
public static void main(String[] args) {
int[] numbers = {10, 20, 30};
int divisor = 0;

try {
// Code that might throw an exception
int result = numbers[1] / divisor; // This will throw ArithmeticException
System.out.println(“Result: ” + result);
} catch (ArithmeticException e) {
// Code to handle the exception
System.out.println(“Error: Division by zero is not allowed.”);
e.printStackTrace(); // Print the stack trace for debugging
}

System.out.println(“Program continues normally…”);
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *