Definition
An exception in Java is an event that disrupts the normal flow of the program. It is an object that represents an error or an unexpected behavior that occurs during runtime. Java uses a class hierarchy for exceptions, which derives from the java.lang.Exception class.
There are two main types of exceptions :
- Checked Exceptions: Exceptions that must be either caught or declared in the method signature using the throws keyword (e.g., IOException, SQLException).
- Unchecked Exceptions: Exceptions that occur due to programming errors, such as NullPointerException, ArrayIndexOutOfBoundsException, and do not need to be declared or caught.
Example
Output Example 1Â (when the user enters 0):
Output Example 2Â (when the user enters 5):
Features of Java Exception Handling
- Java uses a clean and organized approach with try catch and finally blocks .
- Helps developers differentiate between recoverable and programming errors.
- Developers can define their own exceptions by extending the Exception class.
- Java 7 introduced the try-with-resources statement to automatically close resources like files or database connections.
Advantages of Exception Handling in Java
- Helps ensure that the program continues executing even if unexpected conditions arise.
- Keeps the main logic clean by separating error-handling code from regular code.
- Exception can be handled at multiple levels or centrally to simplify debugging.
- Developers are encouraged to anticipate potential issues and handle them, leading to more robust applications.
- Allows for better communication of specific error conditions by creating meaningful, domain-specific exceptions.