An exception is an unexpected event that occurs during program execution. It affects the flow of the program instructions which can cause the program to terminate abnormally.
An exception can occur for many reasons. Some of them are:
- Invalid user input
- Device failure
- Loss of network connection
- Physical limitations (out of disk memory)
- Code errors
- Opening an unavailable file
Java Exception hierarchy
Here is a simplified diagram of the exception hierarchy in Java.
As you can see from the image above, the Throwable class is the root class in the hierarchy.
Note that the hierarchy splits into two branches: Error and Exception.
Java Exception Types
The exception hierarchy also has two branches: RuntimeException and IOException.
1. RuntimeException
A runtime exception happens due to a programming error. They are also known as unchecked exceptions.
These exceptions are not checked at compile-time but run-time. Some of the common runtime exceptions are:
- Improper use of an API - IllegalArgumentException
- Null pointer access (missing the initialization of a variable) - NullPointerException
- Out-of-bounds array access - ArrayIndexOutOfBoundsException
- Dividing a number by 0 - ArithmeticException
You can think about it in this way. “If it is a runtime exception, it is your fault”.
The NullPointerException would not have occurred if you had checked whether the variable was initialized or not before using it.
An ArrayIndexOutOfBoundsException would not have occurred if you tested the array index against the array bounds.
2. IOException
An IOException is also known as a checked exception. They are checked by the compiler at the compile-time and the programmer is prompted to handle these exceptions.
Some of the examples of checked exceptions are:
- Trying to open a file that doesn’t exist results in FileNotFoundException
- Trying to read past the end of a file
Java Exception Handling
We know that exceptions abnormally terminate the execution of a program.
This is why it is important to handle exceptions. Here's a list of different approaches to handle exceptions in Java.
- try...catch block
- finally block
- throw and throws keyword
1. Java try...catch block
The try-catch block is used to handle exceptions in Java.
1class Main {
2 public static void main(String[] args) {
3 try {
4 // code that generate exception
5 int divideByZero = 5 / 0;
6 System.out.println("Rest of code in try block");
7 }
8 catch (ArithmeticException e) {
9 System.out.println("ArithmeticException => " + e.getMessage());
10 }
11 }
12}
Output
ArithmeticException => / by zero
In the example, we are trying to divide a number by 0. Here, this code generates an exception.
To handle the exception, we have put the code, 5 / 0 inside the try block. Now when an exception occurs, the rest of the code inside the try block is skipped.
The catch block catches the exception and statements inside the catch block is executed.
If none of the statements in the try block generates an exception, the catch block is skipped.
2. Java finally block
In Java, the finally block is always executed no matter whether there is an exception or not.
The finally block is optional. And, for each try block, there can be only one finally block.
1class Main {
2 public static void main(String[] args) {
3 try {
4 // code that generates exception
5 int divideByZero = 5 / 0;
6 }
7
8 catch (ArithmeticException e) {
9 System.out.println("ArithmeticException => " + e.getMessage());
10 }
11 finally {
12 System.out.println("This is the finally block");
13 }
14 }
15}
Output
ArithmeticException => / by zero
This is the finally block
In the above example, we are dividing a number by 0 inside the try block. Here, this code generates an ArithmeticException.
The exception is caught by the catch block. And, then the finally block is executed.
3. Java throw and throws keyword
The Java throw keyword is used to explicitly throw a single exception.
When we throw an exception, the flow of the program moves from the try block to the catch block.
Example: Exception handling using Java throw
1class Main {
2 public static void divideByZero() {
3 // throw an exception
4 throw new ArithmeticException("Trying to divide by 0");
5 }
6 public static void main(String[] args) {
7 divideByZero();
8 }
9}
Output
Exception in thread "main" java.lang.ArithmeticException: Trying to divide by 0
at Main.divideByZero(Main.java:5)
at Main.main(Main.java:9)
In the above example, we are explicitly throwing the ArithmeticException using the throw keyword.
Similarly, the throws keyword is used to declare the type of exceptions that might occur within the method. It is used in the method declaration.
Example: Java throws keyword
1import java.io.*;
2class Main {
3 // declaring the type of exception
4 public static void findFile() throws IOException {
5 // code that may generate IOException
6 File newFile = new File("test.txt");
7 FileInputStream stream = new FileInputStream(newFile);
8 }
9 public static void main(String[] args) {
10 try {
11 findFile();
12 }
13 catch (IOException e) {
14 System.out.println(e);
15 }
16 }
17}
Output
java.io.FileNotFoundException: test.txt (The system cannot find the file specified)
0 Comments