9.1. Try-Catch Blocks
Exception handling is a mechanism to handle runtime errors so that the normal flow of the application can be maintained. The try-catch
block is the fundamental construct for handling exceptions in Java.
What are Exceptions?
Exceptions are events that occur during the execution of programs that disrupt the normal flow of instructions. In Java, exceptions are objects that wrap an error event.
Basic Try-Catch Syntax
java
try {
// Code that might throw an exception
riskyOperation();
} catch (ExceptionType name) {
// Code to handle the exception
handleError();
}
Try Block
The try block contains code that might throw an exception. If an exception occurs within the try block, the rest of the code in the try block is skipped.
java
try {
System.out.println("Before risky operation");
int result = 10 / 0; // This will throw ArithmeticException
System.out.println("After risky operation"); // This line won't execute
} catch (ArithmeticException e) {
System.out.println("Exception caught!");
}
Catch Block
The catch block contains exception handling code. It's executed only if an exception of the specified type occurs in the try block.
java
try {
FileReader file = new FileReader("nonexistent.txt");
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
}
Exception Object
The exception object contains information about the error:
java
try {
int[] numbers = {1, 2, 3};
System.out.println(numbers[5]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Message: " + e.getMessage());
System.out.println("Class: " + e.getClass().getName());
e.printStackTrace(); // Prints stack trace to console
}
Complete Example
java
public class BasicTryCatch {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
System.out.print("Enter numerator: ");
int numerator = scanner.nextInt();
System.out.print("Enter denominator: ");
int denominator = scanner.nextInt();
int result = numerator / denominator;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero is not allowed");
} catch (java.util.InputMismatchException e) {
System.out.println("Error: Please enter valid integers");
} finally {
scanner.close();
}
}
}
Key Points
- Try block must be followed by at least one catch or finally block
- Multiple catch blocks can handle different exception types
- Exception handling prevents program termination due to runtime errors
- Always handle specific exceptions rather than using generic Exception class