Java Exception Handling - try catch throw throws finally
1. What is an Exception?
An exception is an abnormal event that disrupts the normal flow of a program at runtime. Java's exception handling mechanism lets you detect, handle, and recover from such events without crashing the program.
Java distinguishes three categories of throwable problems:
| Category | Superclass | Checked? | Examples | When Occurs |
|---|---|---|---|---|
| Checked Exception | Exception |
Yes — compiler enforces handling |
IOException,
SQLException,
ParseException
|
Predictable failures: file not found, bad URL |
| Unchecked Exception | RuntimeException |
No — optional to handle |
NullPointerException,
ArrayIndexOutOfBoundsException, ClassCastException
|
Programming bugs / logic errors |
| Error | Error |
No — not meant to be caught |
OutOfMemoryError,
StackOverflowError
|
Serious JVM problems — typically unrecoverable |
Checked vs Unchecked: Checked exceptions must
be either caught (try-catch) or
declared in the method signature (throws). Unchecked exceptions (RuntimeException subclasses) have no
such requirement — handling is optional.
2. Exception Hierarchy
All exceptions and errors in Java descend from
java.lang.Throwable. Understanding
this hierarchy helps you choose which exceptions to catch and how
broadly.
java.lang.Object
+-- java.lang.Throwable
+-- java.lang.Error (Errors — don't catch these)
| +-- OutOfMemoryError
| +-- StackOverflowError
| +-- VirtualMachineError
+-- java.lang.Exception (Checked exceptions)
+-- IOException
| +-- FileNotFoundException
| +-- EOFException
+-- SQLException
+-- ParseException
+-- ClassNotFoundException
+-- RuntimeException (Unchecked exceptions)
+-- NullPointerException
+-- ArrayIndexOutOfBoundsException
+-- ClassCastException
+-- NumberFormatException
+-- IllegalArgumentException
+-- IllegalStateException
+-- ArithmeticException
+-- UnsupportedOperationException
| Exception | Type | Common Cause |
|---|---|---|
NullPointerException |
Unchecked | Calling a method on a null reference |
ArrayIndexOutOfBoundsException
|
Unchecked | Accessing array index outside valid range |
NumberFormatException |
Unchecked |
Integer.parseInt("abc") — non-numeric string
|
ClassCastException |
Unchecked |
Invalid type casting: (String) new Integer(1)
|
ArithmeticException |
Unchecked | Division by zero: 10 / 0 |
FileNotFoundException |
Checked | Opening a file that doesn't exist |
IOException |
Checked | General I/O failure (network, disk) |
SQLException |
Checked | Database query or connection failure |
StackOverflowError |
Error | Infinite or deeply nested recursion |
3. try-catch Block
The try block contains code that might
throw an exception. The catch block
handles it. Java checks catch blocks
top to bottom — put more specific exceptions
before more general ones.
public class TryCatchDemo {
// Basic try-catch
public static void basicDemo() {
try {
int result = 10 / 0; // throws ArithmeticException
System.out.println(result); // never reached
} catch (ArithmeticException e) {
System.out.println("Caught: " + e.getMessage()); // / by zero
}
System.out.println("Program continues...");
}
// Catching specific exceptions — order matters (specific before general)
public static void multiCatchDemo(String input, int[] arr, int index) {
try {
int parsed = Integer.parseInt(input); // may throw NumberFormatException
int value = arr[index]; // may throw ArrayIndexOutOfBoundsException
int result = parsed / value; // may throw ArithmeticException
System.out.println("Result: " + result);
} catch (NumberFormatException e) {
System.out.println("Bad number format: " + e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index error");
}