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.
- Exception: An event that occurs during program execution that disrupts normal flow.
- Error: Serious problems that cannot be handled by programs (like
OutOfMemoryError). - Exception Classes: All exceptions are subclasses of
java.lang.Exception.
1. Types of Exceptions
- Checked Exceptions:
- Occur at compile-time
- Must be handled using try-catch or throws
- Example:
IOException,SQLException - Unchecked Exceptions (Runtime Exceptions):
- Occur at runtime
- Optional to handle
- 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
- Used to explicitly throw an exception in the program.
- 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
- Declares that a method may throw an exception
- 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
- You can create your own exception class by extending
ExceptionorRuntimeException.
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
- Use try-catch for handling exceptions
- finally block executes always
- throw is used to explicitly throw an exception
- throws declares possible exceptions for a method
- Custom exceptions help in business logic validation