Exception handling in Java

Kavindu Gayantha
Analytics Vidhya
Published in
5 min readApr 3, 2022
HPhoto by Shahadat Rahman on Unsplash

Hi fellows, have you heard about exceptions? Nope?🧐🤔. It’s OK 😉. It’s simply an error. 😌. When programming, we need to consider those kinds of errors. Those are called exceptions. So we should have to be aware of handling those exceptions as a programmer. The errors that occur in the compile-time can be identified by the compiler, they can be fixed easily but not the errors in the run time can be identified by the compiler. So we need to know them and should know the way of handling for not occurring those exceptions in our java code.

Here we go.

why we should handle the exceptions?

statement line 1;
statement line 2;
statement line 3; // exception occurs here
statement line 4;
statement line 5;

Just imagine a situation that a code exists with lines of codes of 5 and an exception occurs in the line of 3, so after that line, the code is not running unless we don’t handle that exception. That’s why we need to know how to handle run-time errors ( exceptions ). Now let’s see how to handle them.

How can we handle the exceptions without knowing about them? 😉. Just go to find what those exceptions are first.

There are two types of exceptions

  • Checked
  • Unchecked

according to Oracle, there is another type called error.

Alright, now see each of them.

Checked exceptions

Checked exceptions are the exceptions that are checked at the compile time. If some code within a method throws a checked exception, then the method must either handle the exception or it must specify the exception using the throws keyword. The compiler knows when file handling, there can be an exception occur. And also when a database connection, if the database does not exist then an exception occurs (SQLException ). In that case we need to handle them definitely otherwise the program will not be run smoothly.

examples for checked exceptions

  • IOException
  • SQLException
  • ClassNotFoundException

Now you might have a doubt.🤔. Since the exceptions occur in the run time, checked exceptions are checked in the compile time. What is that? doubting compile-time and the run time. 🤔.

Don’t be confused. That means checked exceptions are considered as known exceptions which occur in the run time but it is checked in the compile-time and identified by the compiler as an exception.

EX: If we get data from a file since there is no such file at that location, how can we get data from such a file.🤔. Got it?. In that case, the compiler knows that there will be a problem if there is no such file. Then compiler shows ‘ there is a situation to have an exception so handle that issue and compile it ’. like that, we need to know and remember to have to try-catch block or throws keyword to use when handling a file or connecting to a database( if there is not a database like a name which we mentioned, there will be an exception. ) That is what meant by checked exception.

Unchecked exceptions

Unchecked exceptions are exceptions that are not checked at the compile time. It means if your program is throwing an unchecked exception and even if you didn’t handle that exception, the program won’t give a compilation error. Most of the times these exception occurs due to the bad data provided by the user during the user-program interaction. It is up to the programmer to judge the conditions in advance, that can cause such exceptions and handle them appropriately. All Unchecked exceptions are direct sub classes of RuntimeException class.

examples for unchecked exceptions

  • ArrayIndexOutOfBoundException
  • NullPointerException
  • ArithmaticException
  • NumberFormatException

Are you doubting? let’s see where those exceptions are placed.

The class hierarchy

class hierarchy of exceptions

In this class hierarchy, we are not going to handle those all exceptions. There are some exceptions called serious problems according to this hierarchy they are in names StackOverflowErrors, OutOfMemoryErrors, VirtualMachineErrors like that errors no need to handle. It is very complicated.

Let’s see what the exceptions that we can handle are.

There are two ways of handling an exception.

  1. throw out and ignore
  2. catch and handle

we can either ignore the exception and throw or catch the exception and handle the task of exception handling. When we can’t directly identify where the exception is, we use throws to solve the exception. And also when we know where can an exception occurs we can use try-catch to handle the exception.

Now let’s see checked and unchecked further and how to handle them.

Checked Exception

Here one example of a checked exception.

The output will be like this. Here an exception occurs because the file is not to be found. So FileNotFoundException occurs. So we need to handle those kinds of exceptions. checked means it checked when compiling time by the compiler whether this kind of exception can occur or not.

Exception in thread "main" java.io.FileNotFoundException: B:/myfile.txt (No such file or directory)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:93)
at Example.main(Example.java:6)

let’s see how to handle them like this.

As I previously mentioned there are two types of exception handling. Now see how both types are working with an exception with those example codes.

using throws

This is how to handle IOexception with throws.

Let’s see how to handle that exception with try-catch block.

using try-catch

in the lines of codes with file handling parts can be having exceptions so that those lines are covered by the try-catch block. That is how we can handle the exceptions which occur in the run time.

Multi-catch block

Now let’s see how we can handle more than one exception at the same time. In early java versions ( before java 7 ) we can’t handle exceptions in one catch block. we had to write each exception separately.

But in new versions of java, we can handle multiple exceptions in one catch block.

That is an added advantage of new versions of java.

Unchecked Exception

Those are checked in the runtime. So we don’t need to handle it. But we need to be aware of those kind of exceptions and also should have been able to avoid from being occurring an exception. To avoid from them, you need to know what those are, isn’t it? 🤓 Mostly we can see NullPointerExceptions.

NullPointerException occurs when we try to get some values of an object which has not any values assigned. And IndexOutOfBoundsException occurs when we try to access wrong index of an array or list or something like that. example:

int[] arr = new int[10]
for(int a = 0; a <= 10; a++) {
System.out.println(arr[a]);
}
// array size is 10
// but array indexes are 0,1,2,3,4,5,6,7,8,9 only

Like this situations the program try to access indexes of that array which are beyond the limit of array indexes. So the program gives an exception IndexOutOfBound. Those kind of exceptions are found in the run time.

That’s how we can handle exceptions in java. Hope you learnt something. Until we meet again, bye for now. 👋👋

About the author

Kavindu Gayantha

B.Sc(Hons) in Software Engineering

University of Kelaniya, Sri Lanka

--

--

Kavindu Gayantha
Analytics Vidhya

Software Engineering final year undergraduate of University of Kelaniya, Sri Lanka