Exception Handling in Java
Subject: Data Structures and Algorithms · Language: Java · Level: beginner · 6 min read
Learn errors, exceptions, try, catch, finally, throw, and why exception handling keeps programs stable.
An exception is an unexpected problem that happens while a program is running. The program may compile correctly, but still fail during execution because of invalid input, invalid index, division by zero, missing file, or null reference. Exception handling helps a Java program respond to such problems in a controlled way instead of crashing suddenly. A good program should not confuse the user with a long error message when the problem can be handled clearly.
For beginners, exception handling is important because it teaches the difference between normal flow and error flow. Normal flow means the program runs as expected. Error flow means something unusual happened and the program needs a backup response.
try and catch
The `try` block contains code that may cause an exception. Java first tries to run this code normally. The `catch` block handles the exception if it occurs. If the code inside `try` fails with the matching exception type, Java immediately moves to the matching `catch` block.
```java
try {
int result = a / b;
} catch (ArithmeticException e) {
System.out.println("Division by zero is not allowed");
}
```
Here, division by zero may cause `ArithmeticException`. Instead of stopping the program suddenly, the `catch` block prints a clear message.
finally Block
The `finally` block runs whether an exception occurs or not. It is commonly used for cleanup work such as closing files, closing database connections, or releasing resources. A `finally` block is not required in every program, but it is useful when some cleanup must happen in all cases.
throw Keyword
`throw` is used when we want to create and send an exception manually. It is useful when a value is invalid and the program should clearly report that problem.
```java
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative");
}
```
This kind of validation is common in real projects, but beginner programs usually start with `try` and `catch` first.
Common Exceptions
- `ArithmeticException` occurs during invalid arithmetic operations, such as division by zero
- `ArrayIndexOutOfBoundsException` occurs when an invalid array index is used
- `StringIndexOutOfBoundsException` occurs when an invalid string index is used
- `NullPointerException` occurs when a null reference is used incorrectly
- `NumberFormatException` occurs when text cannot be converted into a number
Understanding common exceptions helps students debug programs faster. When the compiler output shows an exception name, read the name carefully because it usually tells what went wrong.
Checked and Unchecked Exceptions
Checked exceptions are checked by the compiler. These usually happen with external resources such as files or databases. The compiler asks the programmer to handle them.
Unchecked exceptions happen during runtime and are usually caused by programming mistakes, such as invalid index or division by zero. Most beginner examples deal with unchecked exceptions.
Exception Handling in DSA
In DSA problems, we do not usually wrap every line in `try catch`. Instead, we write correct conditions to avoid exceptions. For example, check `b != 0` before division and make sure an array index stays between `0` and `length - 1`.
Still, learning exception handling is useful because it helps you understand runtime errors shown by the compiler and fix them properly.
Example Program
```java
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); System.out.print("Enter two numbers: ");
int a = sc.nextInt();
int b = sc.nextInt(); try {
System.out.println("Result = " + (a / b));
} catch (ArithmeticException e) {
System.out.println("Division by zero is not allowed");
}
System.out.println("Program completed");
}
}
``` This program tries to divide two numbers. If the second number is zero, Java throws `ArithmeticException`, and the `catch` block prints a friendly message. The final line still runs, so the user knows the program completed.
Practice Question
Take two numbers and divide them. If the second number is zero, print a proper error message. Then update the program to always print `Program completed` at the end.