Java Exception Handling Interview Question
Java Exception Handling Interview Question
Answer: Exception handling in Java is a mechanism that helps manage runtime errors,
ensuring the smooth flow of program execution. It allows a program to catch and handle
exceptions (abnormal events) that occur during the execution of a program. Without proper
exception handling, the program may terminate unexpectedly. Java provides try, catch,
finally, throw, and throws keywords to handle exceptions.
2. What are the types of exceptions in Java?
Answer:
• Checked Exceptions: These are exceptions that are checked at compile-time. The
Java compiler ensures that these exceptions are handled or declared in the method
signature using the throws keyword. Examples include IOException, SQLException,
and ClassNotFoundException.
• Unchecked Exceptions: These exceptions are checked at runtime, meaning the
compiler does not enforce handling them. They typically occur due to programming
errors, such as logical bugs or improper use of API methods. Examples include
NullPointerException, ArrayIndexOutOfBoundsException, and ArithmeticException.
3. What is the difference between throw and throws?
Answer:
• throw: Used to explicitly throw an exception from any block of code. You can throw
both checked and unchecked exceptions using throw. Example:
throw new NullPointerException("This is a null pointer exception");
• throws: Used in the method declaration to indicate that a method might throw one
or more exceptions. The calling method must handle or declare the exception(s).
Example:
public void readFile() throws IOException {
// Code that may throw IOException
}
4. Explain the try-catch block.
Answer: The try-catch block is used to handle exceptions. Code that might throw an
exception is enclosed in the try block, and the code to handle the exception is placed in the
catch block. This prevents the program from crashing and allows it to continue running or
exit gracefully.
try {
// Risky code
} catch (ExceptionType e) {
1. Definition
• Exception: An exception is an event that occurs during the execution of a program
that disrupts its normal flow. Exceptions are typically conditions that a program can
catch and handle. They arise from issues that are expected, such as invalid input,
failed I/O operations, or arithmetic errors.
• Error: An error indicates serious problems that are typically outside the control of the
application. Errors usually represent conditions that cannot be recovered from, such
as system-level issues or critical resource failures (e.g., running out of memory).