exceptions in java, checked and unchecked

problem

You want to write a program in Java that when an error occurs it does not crash, instead it deals with it in a user-friendly way. To do this, we can use Exceptions.

exceptions in java

Java has the built-in feature of Exceptions for the programmers to use and handle errors. An Exception is used to signal an error/ something went wrong during execution of the program. For example, the program tries to open a file but cannot locate it.

An Exception is simply a class that holds information about the error. For example the error description and where it occurred (its stacktrace).

EXAMPLE - ArrayIndexOutOfBoundsException

The code below will try to access an item in an array that doesn’t exist, causing the program to crash!

				
					package com.programmerabroad;

public class ExceptionExampleArray {

    public static void main(String[] args) {

        int numbers[] = new int[10];

        //try to print an item that doesn't exist
        System.out.println(numbers[20]);
    }
}

				
			

output

IndexOutOfBoundsException java

The program crashed right after executing because the index 20 is out of bounds in array numbers. It’s index ranges from 0 to 9 inclusive. This is a type of Exception that happens at runtime. This one couldn’t be identified by the compiler. However, there are exceptions that can be found at compile time. Let’s see more about these two types below.

Checked and unchecked exceptions

The one above is an example of Unchecked Exception. Other examples of this type include the following:

Some examples of Checked Exceptions include the following:

EXAMPLE - Checked Exception - IOException

				
					package com.programmerabroad;

import java.nio.file.Files;
import java.nio.file.Paths;

public class ExceptionExampleFile {
    
    public static void main(String[] args) {

        Files.readAllLines(Paths.get("notFound.txt"));

    }
}

				
			

output

unreported exception java

The code above fails to compile due to the checked Exception. One of the benefits is that it’s acting as an extra safe-guard of the code. This is one of the main differences between Checked and Unchecked Exceptions.

The compiler can tell that in this case (line 10) the code can throw an Input/ Output Exception so it’s forcing the programmer to insert code for handling the Exception.

handling exceptions

option 1 - declaring it

One way for handling the exception is by declaring it at the method name as shown below:

				
					package com.programmerabroad;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class ExceptionExampleFile {

    public static void main(String[] args) throws IOException {

        Files.readAllLines(Paths.get("notFound.txt"));

    }
}
				
			

The method main simply declares that it can throw an IOException so the one that will be invoking it should deal with handling the Exception. In this case it’s on the Operating System which is the one executing the entry point of the program.

option 2 - handling it with a try/ catch statement
				
					package com.programmerabroad;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class ExceptionExampleFile {

    public static void main(String[] args) {

        try {
            Files.readAllLines(Paths.get("notFound.txt"));
        } catch (IOException e) {
            e.printStackTrace(); //error occurred
        }
    }
}

				
			

In this case we use the try/ catch statement. This is for safeguarding the sensitive code (in this case line 12) and avoid it from crashing. We put inside a try block the line of code that might crash and later on we specify the catch statement followed by a block of code that is executed in the case of the error occurred.

output

NoSuchFileException screenshot

It prints the stacktrace (line 14) and the program exits with code 0 – no errors. We got the NoSuchFileException but the program still didn’t crash.

We can replace line 14 with something more custom like the following:

				
					package com.programmerabroad;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class ExceptionExampleFile {

    public static void main(String[] args) {

        try {
            Files.readAllLines(Paths.get("notFound.txt"));
        } catch (IOException e) {
            System.err.println("Error occurred reading the file. Please check and try again");
        }
    }
}

				
			

output

System.err.println

The stacktrace is more destined for the programmer and not the user. We replaced that with a more compact description that is more user-friendly.

hierarchy in exceptions

All the exceptions given by Java are extending the Exception class. For example the IOException extends the Exception as shown below:

Extends Exception

If we wish we can create our own Exception and extend the Exception.

catching multiple exceptions

In the catch statement we can specify more than one Exception type. Also it’s a good practice when specifying Exceptions to be as specific as possible. For example catch IOException instead of the generic Exception. It helps optimize the code.

Throwing exception

				
					    public static void testException() throws Exception {
        throw new Exception();
    }
				
			

We can also throw an Exception from our method if needed. Simply use the throw keyword followed by a new instantiation of the exception type you wish.

running it

				
					package com.programmerabroad;

public class ExceptionThrowExample {

    public static void main(String[] args) throws Exception {
        testException();
    }

    public static void testException() throws Exception {
        throw new Exception();
    }
}

				
			

In this case the Exception is not handled but instead declared to the method. As it can be seen from the example above, the Exception thrown can be “carried” meaning one method that throws it to the one invoked it can pass it to the other one and so on until someone inevitably deals with it.

Also a method can declare that throws more than one type of Exception. See this post.

conclusion

In this post we saw how to handle Exceptions in our Java programs. There are two types of Exceptions, the checked and unchecked exceptions. We can either handle the exception with a try/ catch statement or we can declare it on the method signature so it’s carried to the invoker.

Share it!

Facebook
Twitter
LinkedIn
Reddit
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x