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.
Contents
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
import java.util.Scanner;
public class ExceptionHandlingExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Read user input
System.out.print("Enter a number to divide 10 by: ");
int userInput = scanner.nextInt();
try {
// Try to divide 10 by user input
int result = 10 / userInput;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
// Catch ArithmeticException (e.g., division by zero)
System.out.println("Error: Cannot divide by zero.");
} finally {
// Finally block always executes
System.out.println("Execution completed.");
}
scanner.close();
}
}
Output Example 1Â (when the user enters 0):
Enter a number to divide 10 by: 0
Error: Cannot divide by zero.
Execution completed.
Output Example 2Â (when the user enters 5):
Enter a number to divide 10 by: 5
Result: 2
Execution completed.
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.