Exceptions in Java
Introduction
When you run a Java program, sometimes things go wrong. Maybe you're trying to divide a number by zero, or you're reading a file that doesn't exist. In Java, these "unexpected events" are called exceptions.
What is an Exception?
An exception is an event that disrupts the normal flow of a program. It’s a runtime error — something Java didn’t expect to happen while your code was running.
For example:
public class DivideByZero {
public static void main(String[] args) {
int result = 10 / 0;
System.out.println("Result: " + result);
}
}
Exception in thread "main" java.lang.ArithmeticException: / by zero
Notice that Java didn’t just crash silently. It gave a detailed message — the type of error and the line where it happened. That’s part of what makes Java’s exception system so developer-friendly.
Types of Exceptions in Java
1. Checked Exceptions
These are exceptions that Java forces you to handle at compile time. They typically deal with external resources like files, databases, or network connections.
import java.io.File;
import java.io.FileReader;
public class CheckedExample {
public static void main(String[] args) throws Exception {
File file = new File("myfile.txt");
FileReader reader = new FileReader(file); // May throw FileNotFoundException
}
}
Java won't compile this code unless you either handle the exception with a try-catch
block or declare it with throws
.
2. Unchecked Exceptions
These are runtime exceptions, and Java does not require you to catch or declare them. Common examples include:
ArithmeticException
NullPointerException
ArrayIndexOutOfBoundsException
public class UncheckedExample {
public static void main(String[] args) {
String str = null;
System.out.println(str.length()); // NullPointerException
}
}
Exception in thread "main" java.lang.NullPointerException
Java Exception Hierarchy
All exceptions are part of the Throwable
class. Here's a simplified view:
- Throwable
- Error – Serious problems (e.g., OutOfMemoryError)
- Exception
- Checked Exceptions – must be handled
- Unchecked Exceptions – can be optionally handled
How to Handle Exceptions in Java
1. try-catch Block
This is the most common way to catch exceptions.
public class TryCatchExample {
public static void main(String[] args) {
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Caught an exception: " + e.getMessage());
}
}
}
Caught an exception: / by zero
2. Multiple catch Blocks
Different exceptions can be caught separately.
public class MultiCatchExample {
public static void main(String[] args) {
try {
int[] nums = {1, 2};
System.out.println(nums[5]);
} catch (ArithmeticException e) {
System.out.println("Arithmetic error");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index error");
}
}
}
Array index error
3. finally Block
This block always runs, whether or not there’s an exception. It's used for cleanup operations.
public class FinallyExample {
public static void main(String[] args) {
try {
int x = 5 / 0;
} catch (ArithmeticException e) {
System.out.println("Handled exception.");
} finally {
System.out.println("Finally block always runs.");
}
}
}
Handled exception.
Finally block always runs.
Using throw to Manually Raise an Exception
public class ThrowExample {
public static void main(String[] args) {
throw new IllegalArgumentException("This is not allowed!");
}
}
Exception in thread "main" java.lang.IllegalArgumentException: This is not allowed!
Using throws to Declare an Exception
If you want to let the caller handle an exception, you can declare it using throws
.
import java.io.FileReader;
public class ThrowsExample {
public static void main(String[] args) throws Exception {
FileReader reader = new FileReader("nofile.txt");
}
}
Exception in thread "main" java.io.FileNotFoundException: nofile.txt (No such file or directory)
Summary
- Exceptions are Java’s way of telling you something went wrong.
- Use
try-catch
to handle errors. finally
always runs, perfect for clean-up.throw
is used to raise exceptions manually.throws
passes the responsibility to the caller.
Comments
Loading comments...