Clean • Professional
Exception handling is an essential part of writing robust Java programs. Java provides several keywords to handle exceptions efficiently.
Java provides several keywords and mechanisms to handle exceptions:

The try block contains the code that might throw an exception.
Syntax:
try {
// Code that may throw an exception
}
catch (ExceptionType e) {
// Handling code
}
Example:
public class TryExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // May throw ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
}
}
}
Output:
Cannot divide by zero!
The catch block handles the exception thrown in the try block.
Example:
try {
int[] arr = {1, 2, 3};
System.out.println(arr[5]); // May throw ArrayIndexOutOfBoundsException
} catch (ArithmeticException e) {
System.out.println("Arithmetic error");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out of bounds");
}
Output:
Array index out of bounds
The finally block always executes, whether an exception occurs or not.
Syntax:
try {
// risky code
} catch (Exception e) {
// exception handling
} finally {
// always executes
}
Example:
try {
int num = 10 / 2;
System.out.println(num);
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
} finally {
System.out.println("This will always execute");
}
Output:
5
This will always execute
The throw keyword is used to explicitly throw an exception in your code.
Syntax:
throw new ExceptionType("Error message");
Example:
public class ThrowExample {
public static void main(String[] args) {
int age = 15;
if (age < 18) {
throw new ArithmeticException("Age must be 18 or above");
}
}
}
Output:
Exception in thread "main" java.lang.ArithmeticException: Age must be 18 or above
The throws keyword is used in method declarations to specify which exceptions might be thrown by that method.
Syntax:
returnType methodName() throws ExceptionType {
// code that may throw exception
}
Example:
import java.io.*;
public class ThrowsExample {
static void readFile() throws IOException {
FileReader file = new FileReader("test.txt");
}
public static void main(String[] args) {
try {
readFile();
} catch (IOException e) {
System.out.println("File not found!");
}
}
}
Output (if file not present):
File not found!