Java Exception Handling – Complete Guide with Examples


Learn Java exception handling, how to handle runtime and compile-time errors using try, catch, finally, throw, and throws keywords, and create custom exceptions for robust Java applications.

Exception Handling in Java – Complete Detailed Tutorial

Exception Handling is a mechanism in Java to handle runtime errors gracefully, without terminating the program abruptly.

  1. Exception: An event that occurs during program execution that disrupts normal flow.
  2. Error: Serious problems that cannot be handled by programs (like OutOfMemoryError).
  3. Exception Classes: All exceptions are subclasses of java.lang.Exception.

1. Types of Exceptions

  1. Checked Exceptions:
  2. Occur at compile-time
  3. Must be handled using try-catch or throws
  4. Example: IOException, SQLException
  5. Unchecked Exceptions (Runtime Exceptions):
  6. Occur at runtime
  7. Optional to handle
  8. Example: ArithmeticException, NullPointerException

2. try, catch, and finally

try: Block of code that may throw an exception.

catch: Block to handle the exception.

finally: Block that executes always, used for cleanup.

Example:


public class Main {
public static void main(String[] args) {
try {
int result = 10 / 0; // may throw ArithmeticException
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero: " + e.getMessage());
} finally {
System.out.println("This block always executes");
}
}
}

Output:


Cannot divide by zero: / by zero
This block always executes

3. throw Keyword

  1. Used to explicitly throw an exception in the program.
  2. Can throw checked or unchecked exceptions

Example:


public class Main {
static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Age must be 18 or older");
} else {
System.out.println("Access granted");
}
}

public static void main(String[] args) {
checkAge(15);
}
}

Output:


Exception in thread "main" java.lang.ArithmeticException: Age must be 18 or older

4. throws Keyword

  1. Declares that a method may throw an exception
  2. Handled by the caller of the method

Example:


import java.io.IOException;

class Demo {
void readFile() throws IOException {
throw new IOException("File not found");
}
}

public class Main {
public static void main(String[] args) {
Demo demo = new Demo();
try {
demo.readFile();
} catch (IOException e) {
System.out.println("Exception caught: " + e.getMessage());
}
}
}

Output:


Exception caught: File not found

5. Custom Exceptions

  1. You can create your own exception class by extending Exception or RuntimeException.

Example:


class AgeException extends Exception {
AgeException(String message) {
super(message);
}
}

class Test {
void checkAge(int age) throws AgeException {
if (age < 18) {
throw new AgeException("Age must be 18 or older");
} else {
System.out.println("Access granted");
}
}
}

public class Main {
public static void main(String[] args) {
Test t = new Test();
try {
t.checkAge(15);
} catch (AgeException e) {
System.out.println("Custom Exception: " + e.getMessage());
}
}
}

Output:


Custom Exception: Age must be 18 or older

6. Key Points

  1. Use try-catch for handling exceptions
  2. finally block executes always
  3. throw is used to explicitly throw an exception
  4. throws declares possible exceptions for a method
  5. Custom exceptions help in business logic validation