Exception Handling in Java | Java Error Types

Sometimes certain events or problems might get triggered during the execution of a program. We need to tackle them with exception handling in Java. If we handle our exceptions then proceed, the proper flow of our program can be stopped from disrupting during execution.

So whilst compilation errors can be sniffed from far away, these errors and exceptions need to be figured out by the programmer himself/herself.

To dumb exceptions down, it’s like you know the train is going to crash and you still get on it.

I am a train I find that offensive meme thomas train meme

There are two types of exceptions in Java:

  1. Checked Exception
  2. Unchecked Exception

One by one we are going to take them up. As for now just know that checked exceptions are checked at compile time whilst the unchecked ones are checked at runtime.

Here’s a pictorial representation of how they fit into their hierarchical classes:

Throwable classes checked unchecked exception labelled diagram

Remember, everything extends Object class the Big Daddy of all classes in Java. We are going to learn about Object class at a later stage.

NOTE: In Java everything under Error and RunTimeExceptions are unchecked. Rest all are checked.

Let’s understand what are checked and unchecked exceptions first, before moving on to exception handling in Java.

Checked Exception

Checked exceptions are those that are checked at compile time. If your code is throwing a checked exception meaning you will know at compile time itself, that there’s a situation that you need to handle.

A very good example of a checked exception is that of a File Reading or writing program that we had learnt in how to read a text file chapter.

We are going to see that here again so you grasp the fundamentals behind a checked exception. I am going to make use of FileReader and BufferedReader’s readLine() method to read a file called NoExceptions.txt located on my E: drive.

Example 1

trying to read a file in java without handling exceptions

Notice how there are two red marks saying there is something wrong with the code? That’s the compile time check coming up with issues.

Okay so when I take my mouse at the cross symbols one by one, both are talking about not handling two exceptions namely:

  • FileNotFoundException
  • IOException

Since they have already highlighted that even before I have run the program it’s nothing but a compile time check. Or you can say the aforementioned exceptions are Checked Exceptions.

Unchecked Exception

Unchecked Exceptions are checked at runtime. Meaning there is no way you could or your IDE figure out if there’s going to be an error in your code. If you are smart enough you will find that out beforehand, but you are not. So, be ready for an error message. Don’t worry that error message is going to be pretty self-explanatory, and so you can then handle that exception.

Unchecked exceptions hence are nothing but severe issues that are taken down as fatal situations.

Such fatal situations are reflected by Error class. Probable bugs are reflected by RuntimeException class.

Here’s one quick example of an Unchecked Exception.

Example 2

unchecked exception example program

I have created a scenario where dividing a number by 0 is going to be infinity which Java doesn’t know until compile-time, since it needs to perform the division first. So, if you try to run the above program you are going to get the following result:

unchecked exception error in java

Exception Handling in Java

You might be beginning to fidget as to why I have left both the programs above stranded without a proper closure. Well, I was about to come to that, trying to make you understand how to achieve exception handling in Java.

If you wish to handle exceptions, Java provides you with 5 different keywords to do so. We are going to look at them one by one.

  1. try
  2. catch
  3. throw
  4. throws
  5. finally

These are all exception handlers and the moment you come across an exception in your code, you can make use of the above keywords to handle your exception.

How, you ask?

Read on to find out.

NOTE: We need to create an instance of class Throwable in order to deal with exceptions. To achieve that we have two ways:

  • By using a parameter in catch block
    • e.g. catch (ArithmeticException ae)
  • Creating instance with new
    • e.g. new ArithmeticException(“test”)

Using Try-Catch Block

One of those ways of exception handling in Java is to make use of a try-catch block.

The code that might throw an exception should be covered in ‘try’ block. Every try block should be followed either by a ‘catch’ block or a ‘finally’ block. These blocks try to handle the exception in a way you desire.

There’s a syntax that we need to follow while trying to handle an exception using try-catch:

try {

----code that might throw an exception----

} catch (ExceptionName e1) {

}

So to understand exception handling in Java, taking above examples and trying to see if we can handle it using the try-catch block.

We will take the Unchecked Exception example first (Example 2):

catching Arithmetic Exception

Here all I did was put the culprit code inside the try block. Notice I also used the System.out.println(div) statement in the same try block since anything displayed in another block would have served as a different scope, and an error message might have ensued. You gotta use everything inside the try() block.

The catch method is simply supposed to hold messages you need to display. Because JVM displays messages in an unreadable format, we make use of a catch statement to get a desirable understandable message.

If you run the above program it is going to directly take you to the catch statement and show the result as:

You are dividing a no. with a 0 dude!

NOTE: You can use System.out.println instead of System.err.println too. err is generally preferred when you have an error message to display. So your IDE displays it in red color like an error.

Multiple Catch

Moving on to the first example (Example 1). Since there were two exceptions that need handling here, we are going to use multiple catch blocks.

So, identifying the area where exceptions are going to be thrown, let’s put it inside a try block:

exception handling using multiple catch

Notice how we have used individual Exception names to identify them apart and handle them. That’s how you gotta do it.

Now if you will run the above program it will read the file NoExceptions.txt since both the Exceptions were handled successfully, and the program will run smoothly:

result of reading from a file program

Yes, the file had that written in it.

NOTE:

  • A catch block cannot exist without a try block.
  • A try block cannot exist without a catch or finally to end it.
  • When trying to catch exceptions more specific exceptions must be listed before general exception i.e. subclasses must be caught before superclasses or the compilation would fail.

Finally Block

Now that we have understood try-catch block let’s move on to the next part in learning exception handling in Java – “Finally”.

Ah! Finally!

Generally, we use finally when there is something important to execute. The reason being, finally always executes. So whether or not your exception is handled, finally block will still be executed.

‘Finally’ comes in handy to put in codes like close() file or connection so as to take care of the crumbs as you go.

The Finally block always comes after a try or catch block.

The syntax to remember here is:

try {
----code that might throw an exception----

} catch (ExceptionName e1) {

-----if needed-----

} finally {

}

The catch block is only if required. Finally can come directly after try-catch as well.

Let’s try this on our Example 1:

finally block example in java

Let’s see if finally fits in our Example 2:

usage of finally in ArithmeticException

If you run the above program now, you will get the following result:

You are dividing a no. with a 0 dude!
The Rock has come back to Wrestlemania

Even if we don’t have a catch method, meaning, the exception isn’t handled, finally block will still get executed. Let’s try this as well:

finally block getting executed even without catch

So the bottom line with finally is that no matter what you put inside finally, it’s the piece of block that will get executed no matter what, except for the following situations:

  • There is an exception in finally block itself
  • Thread dies
  • Use of System.exit()
  • Your computer is on fire

Nested Try Block (Handling Exception Java)

At times while exception handling in Java, you might be required to deal with a situation wherein a part of a block might give an error and the entire block itself might give another. During such desperate times, you must take the aid of Nested Try block.

A try block inside a try block is basically what nested try is all about. Here’s the syntax to remember:

try {

-----code that throws an exception-----

      try {
                -----another code that throws an exception-----

             } catch (ExceptionName e1) {
         }

      } catch  (ExceptionName e2) {
}

Let’s put this in our example and see:

using nested try blocks in java

If we run the above we are going to get this:

Starting Point
You are dividing a no. with a 0 dude!
We are in second try block
Array hasn't been defined 
We are off to strange lands.

Java Throw Exception

Another way to deal with exception handling in Java is to make use of throw keyword. We can make use of throw to explicitly plant an exception as well. It’s called a custom exception. That we are going to see in a bit. First, let’s learn where throw fits in exception handling in Java.

Both check and unchecked exception could be thrown using throw keyword.

The syntax to use throw keyword is:

throw exception;

where exception is an instance of a class. Savvy?

We can throw a newly instantiated exception by using the new keyword like this:

throw new ExceptionClass();

Replace the ExceptionClass() with the Exception class whose exception you have caught. It is nothing but an object reference.

Here let’s see an example:

throw instantiation example

Throw can not only be used in a method but also in a static initializer block.

Also, note that throw can be used in place of return in a method. You can choose to extract an exception message from a method.

Throw keyword can also be used to break a switch statement without actually using the break keyword:

int x = 1;

switch (x) {

case 1:
throw new RuntimeException ("First Exception");
case 2:
throw new RuntimeException("Second Exception");
}

Another important thing to remember, whenever a throw statement gets encountered in your code, the next statement meant for execution doesn’t execute.

The control directly transfers to the catch statement to see if the exception is handled there. If it isn’t handled there, it moves on to the next catch block, and so on. If it isn’t handled anywhere, you get a system-generated error message.

Custom Exception

We could choose to create a new exception and throw them explicitly as well. Yes! You heard that right!

We can create our own exception. Such exceptions are known as a user-defined exception or custom exception. However, we need to ensure our custom exception must extend a class of Exception. All exceptions in Java need to be of type Throwable. If we try to throw an object that is not throwable, you will get a compilation error.

Maybe an example will help.

I have created a custom exception class that extends Exception. Remember this is important:

custom exception class in java

Now we will try to throw our newly created user-defined exception in our program:

custom exception example in java

On running the above program this is what we will get:

My! My! We have an exception exceptions.MyCustomException: Drinking is not for kids

So the moment throw was encountered it will not execute the rest of the code and start looking for a catch statement. It finds the catch statement it was looking for, prints whatever it asks of it.

The reason we are getting a string is because, that is what we had defined our custom exception to be like – holding a string as a parameter. So printing an instance of our custom exception is going to print the string.

Exception Propagation

Remember how stack used to work in Java? Well if you don’t you can always flip through the pages and go back to this chapter to see how a stack functions.

When you have an exception scenario with you remember it is first thrown from the top of the stack. If it fails to be caught there, it moves down the stack to the previous method and so on.

In an example like this where there are multiple methods entailed:

exception propagation example with three methods

Now if you run this program pay attention to how the exception propagation would actually be carried out.

The program call will naturally first go in the following manner:

main() ---> method3() ----> method2() ---> method1()

Now, method1() is the place where the exception will occur.

So since it isn’t handled there it will go to the previous method which is method2(). Then it goes to search in the previous one which is method3().

stack memory exception propagation in java

That’s where the exception is handled by a try-catch block.

NOTE: Exception can be handled in any method, be it be main(), method1(), method2() or method()3.

However, there is an exception to exception propagation. (No kidding!)

It doesn’t work for Checked Exceptions.

So if there is a Checked Exception encountered you get a compile-time error nevertheless. In IDEs, you will know since your program wouldn’t budge without handling it.

If you want checked exceptions propagated as well, then you can do so by using throws keyword.

Throws Keyword (Handling Exception Later On in Java)

When you are going to have an exception in your program you can throw it using the throws clause. It is a way of telling JVM that you are going to handle the exception later in your code.

We make use of throws keyword in a method declaration. Remember it is just a declaration. We used to use throw keyword to actually throw an exception.

Here’s the syntax that we need to remember:

returnType methodName throws ExceptionName() {

-----stuff------
}

We must declare checked exceptions using the throws keyword since unchecked exceptions are already under our control. We can easily correct them ourselves.

Using a throws keyword informs the caller of the method about the exception that needs handling. So it’s just trying to help the programmer figure out what are the possible exceptions that need to be handled.

Here is one example of using throws clause in our program:

an example to depict throws in java

If you run the program it will run like a Cheetah!

NOTE: If you are calling a method that declares an exception, you must catch it or declare it.

Rules for Exception Handling whilst Method Overriding

There are a couple of other rules to remember while dealing with exception handling in Java whilst method overriding. These are:

  • If the superclass method has not declared an exception, subclass overridden method cannot declare checked exception but can declare unchecked exception
  • If the superclass method has declared an exception, subclass overridden method can declare the same class exception, subclass exception or no exception but cannot declare parent exception.

When should you throw an Exception?

All that we have learned so far comes down to the aforementioned broiling question. When should we really go for it?

The bottom line of throwing an exception is that you should throw it only for rare exceptional cases and not for the ones that are already in a normal flow of operation. Don’t throw an exception when there is an error that you can handle locally.

Exceptions are supposed to be a rare unforeseen situation. That’s when you should throw it.

That’s all there is to learn about exceptions and exception handling in Java.

Hope that didn’t turn out to be a drag. If it did, you need one. 😉

Scottshak

Poet. Author. Blogger. Screenwriter. Director. Editor. Software Engineer. Author of "Songs of a Ruin" and proud owner of four websites and two production houses. Also, one of the geekiest Test Automation Engineers based in Ahmedabad.

You may also like...

7 Responses

  1. June 7, 2017

    […] We have to handle Interrupted Exception that it might throw. Don’t know about exceptions? Go back and learn about them. […]

  2. February 19, 2018

    […] you aren’t sure how to handle exceptions, feel free to check out that tutorial as […]

  3. March 7, 2018

    […] on Surround with try/catch to handle it. If you wish to see how exceptions are handled you could check out that tutorial as […]

  4. April 2, 2018

    […] you aren’t sure how to handle exceptions, feel free to check out that tutorial as […]

  5. April 6, 2018

    […] return type of the Jsoup.parse method is a document which we have declared. You can handle exceptions by using throws or try catch to catch an IOException which will also take care of […]

  6. July 23, 2019

    […] […]

  7. July 28, 2019

    […] Chapter 17 – Exception Handling […]

Leave a Reply