Java Exceptions
A Java exception is an object that represents an error or unusual problem while a program is running. Exceptions let a program detect a problem and decide how to respond instead of simply crashing without explanation.
You will often see exceptions when code uses invalid input, divides by zero, reads a missing file, or tries to use a value that is null.
Why Exceptions Matter
Without exception handling, many runtime errors stop the program immediately. With exception handling, you can show a helpful message, use a default value, close a resource, or let the rest of the program continue.
Exception handling does not make incorrect code correct. It gives you a controlled way to deal with problems that can happen while the program runs.
The try-catch Statement
Put code that might throw an exception inside a try block. Put the response inside a catch block.
public class Main {
public static void main(String[] args) {
int total = 20;
int count = 0;
try {
int average = total / count;
System.out.println("Average: " + average);
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero.");
}
System.out.println("Program continues.");
}
}
Output:
Cannot divide by zero.
Program continues.
How It Works
The expression total / count tries to divide by zero, so Java throws an ArithmeticException. Java skips the rest of the try block and runs the matching catch block.
After the catch block finishes, the program continues with the next statement after the try-catch.
Common Exception Types
| Exception | Common cause |
|---|---|
ArithmeticException |
Invalid math operation, such as dividing an integer by zero |
NumberFormatException |
Trying to convert text that is not a valid number |
ArrayIndexOutOfBoundsException |
Using an array index that does not exist |
NullPointerException |
Calling a method or accessing a field on null |
Catching Input Conversion Errors
A common beginner example is converting text to a number. Integer.parseInt() works only when the text contains a valid integer.
public class Main {
public static void main(String[] args) {
String input = "45x";
try {
int score = Integer.parseInt(input);
System.out.println("Score: " + score);
} catch (NumberFormatException e) {
System.out.println("Invalid number: " + input);
}
}
}
Output:
Invalid number: 45x
The catch block names the specific exception type it can handle. This is usually better than catching every possible exception, because different problems often need different responses.
The finally Block
A finally block runs after try and catch, whether an exception happened or not. It is commonly used for cleanup work.
public class Main {
public static void main(String[] args) {
String text = "123";
try {
int value = Integer.parseInt(text);
System.out.println("Value: " + value);
} catch (NumberFormatException e) {
System.out.println("Could not parse number.");
} finally {
System.out.println("Finished checking input.");
}
}
}
Output:
Value: 123
Finished checking input.
Checked And Unchecked Exceptions
Some exceptions are checked by the compiler. For example, code that reads a file may need to handle or declare an exception before it compiles.
Other exceptions are unchecked. The examples above are unchecked exceptions because the compiler does not force you to catch them. They still matter because they can stop the program at runtime.
Good Habits
- Catch the most specific exception type you can reasonably handle.
- Use clear messages that help explain what went wrong.
- Do not use exceptions to replace normal
ifchecks for simple conditions. - Keep the
tryblock focused on the code that might fail.
Takeaway: Java exceptions let you handle runtime problems with try, catch, and sometimes finally so your program can respond clearly.
