Java Exception Handling: Complete Guide with Examples
Exception Handling in Java is a powerful mechanism to handle runtime errors, ensuring normal flow of the application. It improves program reliability and prevents unexpected crashes.
What is Exception?
An exception is an unwanted or unexpected event that occurs during program execution and disrupts normal flow.
Example: Division by zero, null reference, file not found.
Types of Exceptions
1. Checked Exceptions
Checked at compile-time. Must be handled using try-catch or declared using throws.
- IOException
- SQLException
2. Unchecked Exceptions
Occur at runtime. Not checked by compiler.
- NullPointerException
- ArithmeticException
3. Errors
Serious problems that cannot be handled.
- OutOfMemoryError
Try-Catch Block
Used to handle exceptions and prevent program termination.
Example
public class Test {
public static void main(String[] args) {
try {
int x = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
}
}
}
Finally Block
The finally block always executes whether exception occurs or not.
Example
try {
int x = 10 / 0;
} catch (Exception e) {
System.out.println("Exception occurred");
} finally {
System.out.println("Always executed");
}
throw Keyword
Used to explicitly throw an exception.
Example
throw new ArithmeticException("Custom error");
throws Keyword
Used to declare exceptions in method signature.
Example
void test() throws IOException {
// risky code
}
Multiple Catch Blocks
A try block can have multiple catch blocks to handle different exceptions.
try {
int a = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Arithmetic Error");
} catch (Exception e) {
System.out.println("General Error");
}
Custom Exception
You can create your own exception by extending Exception class.
Example
class MyException extends Exception {
MyException(String msg) {
super(msg);
}
}
public class Test {
public static void main(String[] args) throws MyException {
throw new MyException("Custom Exception");
}
}
Exception Propagation
Exceptions are propagated from method to method until handled.
class Test {
static void m1() {
int x = 10 / 0;
}
static void m2() {
m1();
}
public static void main(String[] args) {
try {
m2();
} catch (Exception e) {
System.out.println("Handled");
}
}
}
Exception Handling Summary
- Exception → runtime error
- try-catch → handle exceptions
- finally → always executes
- throw → manually throw exception
- throws → declare exception
Exception Handling FAQ
What is difference between checked and unchecked exceptions?
Checked are compile-time, unchecked are runtime exceptions.
What is finally block?
It always executes regardless of exception occurrence.
Can we have try without catch?
Yes, but must have finally block.