Tuesday, 30 May 2017

Tutorial 24: Handling Exceptions



Exceptions are part of the error-handling functionality of Java. Exception handling is a way to tell your program what to do in case there is an error. So what is an Exception?

An Exception is an object. There are many kinds of exceptions such as FileNotFoundException, IOException and others. All these exceptions are child classes of the Exception class, and the Object class is the ultimate parent class of the Exception class.

There are two ways to handle an exception. One way is to throw the exception using the throws keyword. The other way is to use a try-catch block to handle the exception.
Since this is an introduction to exception handling in Java, we will use a simple example to illustrate both cases.

In a past tutorial, we learnt how to open text files in Java. Let us revisit that example because it will help us learn how to use each of the above two ways: i.e. throwing an exception and using a try-catch block.

So here is the code we used to open a text file in the past tutorial:

public class Person {
            public static void main (String[] args) {
                        File file = new File (C:/Users/Mukami/Desktop/Document2.txt);
                        FileReader fileReader1 = new FileReader (file);
            }
}

Now, Java will show that there is an error in the line where we create a new FileReader object. If you hover your mouse over the error, you will see that there is a warning that the FileReader object is not closed, hence the possibility for a resource leak. What is of concern to us, however, is the other error, which states that the line FileReader fileReader1 = new FileReader(file); throws a FileNotFoundException.

In other words, this means that Java knows that the file might exist or might not exist. So what Java wants you to do is to tell it what it should do in case the file does not exist. 

Throwing an Exception

When you throw an exception, it is like you are throwing the exception object from within the code in which the error occurred. When your method throws an exception and the error actually occurs, like in the above case, the file is not found, then Java will output an error message on the console with details such as the exception and the line of code that threw that exception. So in our example, here is how you throw an exception. This message is referred to as a stack trace:

public class Person {
            public static void main (String[] args) throws FileNotFoundException {
                        File file = new File (C:/Users/Mukami/Desktop/Document2.txt);
                        FileReader fileReader1 = new FileReader (file);
}

So what happens is that if the file is not found, you will get the following output on the console:



Figure 1: Console output when the exception is thrown.

Now, maybe you are asking yourself: Is it only from the main method that we can throw an exception? The answer is “no.” Any method can throw an exception, but ultimately, you have to also handle the exception in the main method. For example, let’s say that we create a method called openFile() that opens a file and call it from within the main method’s body.

public class Person {
            public static void main (String[] args) {
                        openFile();
}
public static void openFile() {
                                    File file = new File (“C:/Users/Mukami/Desktop/Document1.txt”);
                        FileReader fileReader1 = new FileReader (file);
}
}

Java will require that you handle the FileNotFoundException that is thrown from the method. To do this, we can add a throws keyword in the header of the method’s definition like this:

public class Person {
            public static void main (String[] args) {
                        openFile();
}
public static void openFile() throws FileNotFoundException {
                                    File file = new File (“C:/Users/Mukami/Desktop/Document1.txt”);
                        FileReader fileReader1 = new FileReader (file);
}

Now, the error disappears from the method openFile(). However, you will still get an error from the line where the function openFile() is called from within the body of the main function. So, you also have to handle the exception from the main body like this:

public class Person {
            public static void main (String[] args) throws FileNotFoundException {
                        openFile();
}
public static void openFile() throws FileNotFoundException {
                                    File file = new File (“C:/Users/Mukami/Desktop/Document2.txt”);
                        FileReader fileReader1 = new FileReader (file);
}

Now, when you run the program, no error occurs. If the file is not found, then Java will print a stack trace on the console, telling you which line threw the exception. 




Figure 2: Throwing Exceptions

Using a try-catch Block


When we throw an exception using the throws declaration, Java will output a stack trace on the console if it cannot locate the file that you would like to open. However, remember that not all your users are technical. Most of the people using your program don’t understand Java, or exception. They don’t even understand what a stack trace is. This is why we use a try-catch block because we can give the user more detailed and user-friendly information about the error instead of the stack trace, which most people find scary.

If we were trying to open the same file we’ve been dealing with in this tutorial, here is how we would write it in a try-catch block:

try {
            File file = new File (“C:/Users/Mukami/Desktop/Document2.txt”);
            FileReader fileReader1 = new FileReader (file);
            } catch (FileNotFoundException e) {
                        e.printStackTrace();
}


Figure 3: Using a try-catch block.


Now, what we are telling Java in the above try-catch block is to try to execute the code within the curly braces of the try block. If there is no error, it should then continue with the other lines in the try block and not do anything with the catch block.

However, if an error occurs, like in our case, the file is not found, then the code within the catch block is executed. Java will not run any other code in the try block. So if the file is not found by the above try block, Java will do whatever is in the catch block. In this case, it will print a stack trace just like the throws exception method we looked at earlier. 

With the try-catch block, you could, for example, output user-friendly information. For instance, you can use System.out.println(); to output the cause of the error to the user like this:

public class Person {
            public static void main(String[] args) {
                        File file = new File ("C:/Users/Mukami/Desktop/Document2.txt");
                        try {
                                    FileReader fileReader1 = new FileReader (file);
                                    } catch (FileNotFoundException e) {
                                                System.out.println("File not found: " + file.toString());
                        }
            }
           
}



Figure 4: A try-catch block with user-friendly information


That’s all for this tutorial. In case of any comments or questions, please drop them in the comments section below and I will address them.

In the next tutorial, we are going to look further into throwing exceptions.

Take care until next time.  

No comments:

Post a Comment