Java Exception Handling Introduction
In this page:
What is an Exception?
An exception is an object Java creates and throws when something disrupts a program's normal flow, like dividing by zero or accessing a null reference. Instead of letting the program crash outright, Java lets you catch that object and decide how to respond.
Example: What is an Exception?
public class Main {
public static void main(String[] args) {
try {
int result = 10 / 0; // throws ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}
Login to try C/C++/Java/PHP code in the editor
Checked vs Unchecked Exceptions
Checked exceptions (like IOException) must be declared or caught at compile time because the compiler forces you to acknowledge the failure is possible; unchecked exceptions (like NullPointerException) extend RuntimeException and can surface without any such warning.
Example: Checked vs Unchecked Exceptions
public class Main {
public static void main(String[] args) {
try {
throw new RuntimeException("Unchecked"); // no need to declare it
} catch (RuntimeException e) {
System.out.println(e.getMessage());
}
}
}
Login to try C/C++/Java/PHP code in the editor
Why Handle Exceptions?
Handling exceptions keeps one failure from silently corrupting program state or crashing the whole application. It also lets you give the user a meaningful message instead of a raw stack trace, or fall back to a safe default and keep running.
Example: Why Handle Exceptions?
public class Main {
public static void main(String[] args) {
try {
int[] arr = new int[2];
System.out.println(arr[5]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Handled gracefully instead of crashing");
}
}
}
Login to try C/C++/Java/PHP code in the editor
Common Exception Types
Some of the exceptions you'll hit constantly include NullPointerException (calling a method on null), ArrayIndexOutOfBoundsException (invalid array index), and ArithmeticException (like dividing an int by zero). Recognizing these by name speeds up debugging considerably.
Example: Common Exception Types
public class Main {
public static void main(String[] args) {
try {
String s = null;
s.length();
} catch (NullPointerException e) {
System.out.println("Caught a NullPointerException");
}
}
}
Login to try C/C++/Java/PHP code in the editor
The try-catch-finally Concept
The try block holds code that might fail, catch defines how to respond if it does, and finally runs regardless of whether an exception occurred — typically used to release resources like open files or network connections.
Example: The try-catch-finally Concept
public class Main {
public static void main(String[] args) {
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Error occurred");
} finally {
System.out.println("Runs regardless");
}
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: