In Java, an exception is an unexpected event that interrupts the normal flow of a program. Exceptions happen during runtime when a program encounters problems like division by zero, accessing an invalid array index, or handling a null reference. Understanding when these exceptions occur in a code sequence is important for writing robust and error-free applications.
Table of Content
Different Types of Exceptions in Java
Java exceptions are classified into :
- Built-In Functions
Built-in functions are the pre-defined functions used to handle common errors in Java. These are of two types.
- Checked Exceptions – Checked at compile time. Examples:
- FileNotFoundException
- ClassNotFoundException
- IOException
- InstantiationException
- SQLException
- InterruptedException
- Unchecked Exceptions – Occurs at runtime, based on a logical error. Examples:
- ArithmeticException
- ClassCastException
- NullPointerException
- ArrayIndexOutOfBoundsException
- ArrayStoreException
- IllegalThreadStateException
- User-Defined Functions
- Errors – Irrecoverable problems like OutOfMemoryError.
When Does an Exception Arise?
Exceptions can arise at two points in a Java program:
- During Compilation
- During Runtime
1. During Compilation (Checked Exceptions)
Checked exceptions are identified at compile-time, which means your program won’t compile unless they are handled.
Example of Checked Exception:
Get 100% Hike!
Master Most in Demand Skills Now!
File Not Found (FileNotFoundException)
It occurs when you are trying to attempt to read a non-existent file.
In this example, we have tried to read a file that doesn’t exist. Here it will give an exception. Here is the code for the same:
import java.io.File;
import java.io.FileReader;
public class FileReadExample {
public static void main(String[] args) {
File new_file = new File("nonexistent.txt");
FileReader fr = new FileReader(new_file);
}
}
Output:
Exception in thread “main” java.io.FileNotFoundException: nonexistent.txt (No such file or directory)
Solution: The solution is you can use try-catch or throw an Exception.
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class FileReadExample {
public static void main(String[] args) {
File new_file = new File("nonexistent.txt");
try {
FileReader fr = new FileReader(new_file);
// Proceed with file reading logic here
} catch (FileNotFoundException e) {
System.out.println("File not found: " + new_file.getName());
// Handle exception, log error, or alert user
} catch (IOException e) {
System.out.println("An error occurred while reading the file.");
}
}
}
2. During Runtime (Unchecked Exceptions)
Unchecked Exceptions are not checked at the compile time but during the execution of the program.
Examples of Unchecked Exceptions:
1. Division by Zero (ArithmeticException)
It happens when a number is divided by zero.
int check_result = 20 / 0; // ArithmeticException: / by zero
Solution: The solution to this is to use conditional checks.
if (y != 0) {
System.out.println(x / y);
} else {
System.out.println("Cannot divide by zero");
}
2. Null Object Access (NullPointerException)
It happens when you are accessing a method or a property on a null object.
String test_str = null;
System.out.println(str.length()); // NullPointerException
Solution: The solution is to check for null before accessing.
if (test_str != null) {
System.out.println(test_str.length());
}
3. Array Index Out of Bounds (ArrayIndexOutOfBoundsException)
It occurs when you are trying to access an index that does not exist.
int[] test_arr = {1, 2, 3};
System.out.println(test_arr[5]); // ArrayIndexOutOfBoundsException
Solution: The solution is to check for the index validity.
if (index >= 0 && index < test_arr.length) {
System.out.println(test_arr[index]);
Type Mismatch (ClassCastException)
It happens when you are casting an incompatible object type.
Object obj = new Integer(10);
String test_str = (String) obj; // ClassCastException
Solution: The solution is to use instanceof before casting:
if (obj instanceof String) {
String test_str = (String) obj;
}
How can you Handle Exceptions in Java?
Java gives you several mechanisms for handling exceptions:
1. Try-Catch Block
The try-catch block is used to handle exceptions that may occur during program execution. The try block contains the code that might throw an exception, while the catch block handles the exception if it occurs.
try {
int num = 15 / 0;
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero!");
}
In this example, dividing 15 by 0 throws an ArithmeticException, which is caught by the catch block, and an error message “Error: Division by zero!” is printed.
2. Finally Block (Always Executes)
We generally use Finally block if we want to perform clean up activities like closing files or releasing unnecessary resources. The special characteristic of this block is that it always executes, regardless of whether an exception was thrown or not.
try {
FileReader fr = new FileReader("test1data.txt");
} catch (FileNotFoundException e) {
System.out.println("File not found.");
} finally {
System.out.println("Execution completed.");
}
In this example, whether the file is found or not, the message “Execution completed.” will always be printed.
3. Throws Keyword
You can use this to throw exceptions to the caller. This means that it doesn’t handle the exception itself, but rather passes it to the method that calls it.
public void readFile() throws FileNotFoundException {
FileReader fr = new FileReader("file.txt");
}
In this example, the readFile method declares that it may throw a FileNotFoundException. The calling code must handle this exception using a try-catch block or propagate it further.
Conclusion
In Java, exceptions can happen during compilation (checked) or runtime (unchecked). They are caused due to a number of reasons such as division by zero, null references, out-of-bounds access, and file errors. Using try-catch, finally, and throws is an efficient method of proper exception handling, keeping your programs stable and preventing unexpected crashes. This helps to implement graceful error handling, making applications more robust and reliable.