Java Docs
Java Documentation
Java Exception Handling
In the previous tutorial, we learned about Java exceptions and how they can terminate a program unexpectedly. exception handling allows the program to continue execution smoothly even when something goes wrong.
Approaches to Handle Exceptions
- try...catch block
- finally block
- throw and throws keyword
1. Java try...catch Block
The try...catch block is the most common way to handle exceptions in Java.
try {
// code that may cause an exception
} catch (Exception e) {
// code that handles the exception
}Example: Exception handling using try...catch
class Main {
public static void main(String[] args) {
try {
int divideByZero = 5 / 0;
System.out.println("Rest of code in try block");
}
catch (ArithmeticException e) {
System.out.println("ArithmeticException => " + e.getMessage());
}
}
}Output
ArithmeticException => / by zero
Here, Java skips the remaining code in the try block when an exception occurs. The catch block handles the exception.
2. Java finally Block
The finally block always executes—whether an exception occurs or not. It is often used for closing files, connections, or cleanup tasks.
try {
// code
}
catch (Exception e) {
// handle exception
}
finally {
// this block always runs
}Example: Using finally Block
class Main {
public static void main(String[] args) {
try {
int divideByZero = 5 / 0;
}
catch (ArithmeticException e) {
System.out.println("ArithmeticException => " + e.getMessage());
}
finally {
System.out.println("This is the finally block");
}
}
}Output
ArithmeticException => / by zero This is the finally block
The finally block ensures important code executes regardless of exceptions.
3. Java throw and throws Keyword
Using throw
The throw keyword is used to manually throw an exception.
class Main {
public static void divideByZero() {
throw new ArithmeticException("Trying to divide by 0");
}
public static void main(String[] args) {
divideByZero();
}
}Output
Exception in thread "main" java.lang.ArithmeticException: Trying to divide by 0
Using throws
The throws keyword declares the type of exception a method may generate.
import java.io.*;
class Main {
public static void findFile() throws IOException {
File newFile = new File("test.txt");
FileInputStream stream = new FileInputStream(newFile);
}
public static void main(String[] args) {
try {
findFile();
}
catch (IOException e) {
System.out.println(e);
}
}
}Output
java.io.FileNotFoundException: test.txt (The system cannot find the file specified)
If a method does not handle exceptions internally, it must declare them using the throws keyword.