May 10, 2024

Exception Handling in Java

Exception handling

Exception handling is a mechanism to handle runtime errors in Java programs. It allows you to gracefully handle unexpected situations that may occur during program execution.

You can use try-catch blocks to catch exceptions and handle them. Inside the try block, you write the code that may throw an exception, and in the catch block, you specify how to handle the exception.

Java provides a hierarchy of exception classes, with the base class being Throwable. Exceptions are divided into two categories: checked exceptions and unchecked exceptions.

Examples

// Example 1: Handling NullPointerException
try {
    String str = null;
    int length = str.length(); // This line will throw NullPointerException
} catch (NullPointerException e) {
    System.out.println("NullPointerException caught!");
}

// Example 2: Handling ArithmeticException
try {
    int result = 10 / 0; // This line will throw ArithmeticException
} catch (ArithmeticException e) {
    System.out.println("ArithmeticException caught!");
}

// Example 3: Handling ArrayIndexOutOfBoundsException
try {
    int[] arr = {1, 2, 3};
    int element = arr[3]; // This line will throw ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("ArrayIndexOutOfBoundsException caught!");
}

FAQ (interview questions and answers)

  1. What is an exception in Java?
    An event that disrupts the normal flow of a program's execution
    A syntax error
    A logical error
  2. What is the purpose of a try-catch block?
    To handle exceptions that may occur within a block of code
    To execute a block of code repeatedly
    To define a custom exception
  3. What is the difference between checked and unchecked exceptions?
    Checked exceptions must be caught or declared, while unchecked exceptions do not need to be handled explicitly.
    Checked exceptions occur at compile-time, while unchecked exceptions occur at runtime.
    Checked exceptions are more severe than unchecked exceptions.
  4. What happens if an exception is not caught?
    The program continues execution without any interruption.
    The program terminates with an error message.
    The exception is automatically handled by the Java Virtual Machine.
  5. Can multiple catch blocks be used in a try-catch block?
    No, only one catch block can be used.
    Multiple catch blocks need external libraries.
    Yes, to handle different types of exceptions separately.

Your Total Score: 0 out of 5

Remember to just comment if you have any doubts or queries.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.