Interview Help Desk Exception Handling

Exception Handling

Practice commonly asked Exception Handling interview questions with clear answers and explanations.

3 Interview Questions

Exception Handling Interview Questions

3 Questions
Q 121

What is the purpose of a try block?

Easy
Answer
A try block contains code that may throw an exception and needs exception handling.
Explanation
The try block defines the portion of code whose failures are handled by one or more matching catch blocks or followed by a finally block. It should contain the operation that may actually fail rather than wrapping a large unrelated section of application code.
Code Example Java
try {
    Student student = studentService.findById(studentId);
    System.out.println(student.getName());
} catch (StudentNotFoundException e) {
    System.out.println("Student was not found");
}
Reference: Java Exception Handling
Q 122

What is the difference between a checked and an unchecked exception?

Easy
Answer
Checked exceptions are checked by the compiler, while unchecked exceptions are RuntimeException subclasses that are not required to be declared or caught.
Explanation
A checked exception usually represents a condition that the application is expected to consider, such as an I/O failure. The compiler requires the method to catch it or declare it with throws. Unchecked exceptions usually indicate programming errors, invalid arguments, or invalid object state. The compiler does not force the developer to handle them.
Code Example Java
static String readFile() throws IOException {
    return Files.readString(Path.of("data.txt"));
}

static void setAge(int age) {
    if (age < 0) {
        throw new IllegalArgumentException("Age cannot be negative");
    }
}
Reference: Java Exception Handling
Q 123

What is exception handling in Java?

Easy
Answer
Exception handling is a mechanism used to detect, handle, and recover from abnormal conditions that occur during program execution.
Explanation
Exception handling separates normal application flow from failure-handling logic. Java provides try, catch, finally, throw, and throws to deal with exceptions. Good exception handling does not mean catching every exception; it means handling a failure where the application can take a meaningful action, recover, translate the exception, or provide useful information to the caller.
Code Example Java
try {
    int age = Integer.parseInt(input);
    System.out.println("Age: " + age);
} catch (NumberFormatException e) {
    System.out.println("Please enter a valid age");
}
Reference: Java Exception Handling

About This Topic

Prepare for Exception Handling interviews with important concepts and commonly asked questions.