Java Exception-interview
Q1. What is an Exception in Java?
An Exception is an unwanted event that disrupts the normal flow of a program during runtime. It is an object of the Throwable class and can be handled using try-catch blocks.
Q2. What are the main types of Exceptions in Java?
- Checked exceptions → Compile-time exceptions (e.g., IOException, SQLException).
- Unchecked exceptions → Runtime exceptions (e.g., NullPointerException, ArithmeticException).
- Errors → Serious issues that cannot be recovered (e.g., OutOfMemoryError).
Q3. How is Exception Handling done in Java?
Exception handling is performed using:
- try → Block of code to monitor for exceptions.
- catch → Handles the exception.
- finally → Executes always, used for cleanup code.
- throw → Used to explicitly throw an exception.
- throws → Declares exceptions a method can throw.
Q4. Difference between throw and throws in Java?
- throw → Used to explicitly throw an exception object.
- throws → Declares exceptions that a method might throw.
Q5. Why is Exception Handling important in Java?
- It prevents program termination during runtime errors.
- Makes applications more robust and reliable.
- Provides a structured way to detect and recover from errors.