What is an Exception?
An exception is an abnormal condition that disrupts the normal flow of a program at runtime. Java provides a robust mechanism to handle such conditions gracefully.
| Type of Error | Phase | Example |
|---|---|---|
| Syntax Error | Compile time | Missing semicolon, wrong keyword |
| Logical Error | Runtime (wrong output) | Wrong formula used |
| Runtime Exception | Runtime (crash) | Divide by zero, null pointer |
Exception Hierarchy
All exceptions in Java are subclasses of Throwable:
java.lang.Object
โโโ java.lang.Throwable
โโโ java.lang.Error (JVM errors โ do NOT handle)
โ โโโ OutOfMemoryError
โ โโโ StackOverflowError
โ โโโ VirtualMachineError
โโโ java.lang.Exception (handle these)
โโโ Checked Exceptions (compile-time)
โ โโโ IOException
โ โโโ SQLException
โ โโโ FileNotFoundException
โโโ RuntimeException (unchecked)
โโโ ArithmeticException
โโโ NullPointerException
โโโ ArrayIndexOutOfBoundsException
โโโ ClassCastException
โโโ NumberFormatException
๐ก Did You KnowChecked exceptions must be handled or declared. Unchecked exceptions (RuntimeException subclasses) are optional to handle. Errors should never be caught.
try-catch-finally
public class ExceptionDemo {
public static void main(String[] args) {
int[] arr = {10, 20, 30};
try {
int result = arr[0] / 0; // ArithmeticException
arr[5] = 99; // ArrayIndexOutOfBoundsException
} catch (ArithmeticException e) {
System.out.println("Math error: " + e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array error: " + e.getMessage());
} finally {
System.out.println("Finally always executes!");
}
}
}๐ Key Point
finally always executes โ even if a return is in the try block, or an exception is thrown that is not caught. It is used to release resources.throw & throws
| Keyword | Purpose | Used in |
|---|---|---|
throw | Manually throw an exception object | Inside a method body |
throws | Declare that a method may throw an exception | Method signature |
// Using 'throw' to manually throw an exception
static void validateAge(int age) {
if (age < 18)
throw new IllegalArgumentException("Age must be 18 or above: " + age);
System.out.println("Valid age: " + age);
}
// Using 'throws' to delegate handling to caller
static void readFile(String path) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(path));
System.out.println(br.readLine());
br.close();
}
public static void main(String[] args) {
try {
validateAge(15);
readFile("data.txt");
} catch (IllegalArgumentException | IOException e) {
System.out.println("Error: " + e.getMessage());
}
}Multiple catch Blocks
Multiple catch blocks allow handling different exception types separately. Catch order matters โ more specific exceptions must come before general ones.
try {
String s = null;
s.length(); // NullPointerException
int x = Integer.parseInt("abc"); // NumberFormatException
} catch (NullPointerException e) {
System.out.println("Null: " + e);
} catch (NumberFormatException e) {
System.out.println("Format: " + e);
} catch (Exception e) {
// catches any other Exception โ must be LAST
System.out.println("General: " + e);
}โ ๏ธ ImportantIf a parent exception class (like
Exception) appears before a child (like NullPointerException), a compile-time error occurs: 'exception already caught'.Nested try
try {
System.out.println("Outer try");
try {
int x = 10 / 0; // handled in inner catch
} catch (ArithmeticException e) {
System.out.println("Inner catch: " + e.getMessage());
throw new RuntimeException("Re-thrown"); // escalate
}
} catch (RuntimeException e) {
System.out.println("Outer catch: " + e.getMessage());
}User-defined Exceptions
Create custom exceptions by extending Exception (checked) or RuntimeException (unchecked).
// Custom checked exception
class InsufficientFundsException extends Exception {
private double amount;
InsufficientFundsException(double a) {
super("Insufficient funds. Need: โน" + a);
amount = a;
}
double getAmount() { return amount; }
}
class BankAccount {
double balance = 1000;
void withdraw(double amt) throws InsufficientFundsException {
if (amt > balance)
throw new InsufficientFundsException(amt - balance);
balance -= amt;
}
}Common Built-in Exceptions
| Exception | Cause |
|---|---|
| ArithmeticException | Division by zero |
| NullPointerException | Accessing method/field on null reference |
| ArrayIndexOutOfBoundsException | Array index < 0 or >= length |
| NumberFormatException | Invalid string-to-number conversion |
| ClassCastException | Invalid type casting |
| StackOverflowError | Infinite recursion |
| FileNotFoundException | File path does not exist |
| IOException | General I/O failure |
| StringIndexOutOfBoundsException | String index out of range |
Download PDF Notes
Save these notes as a PDF for offline reference