Exception Handling in Java with examples

Exception Handling

Exception handling allows Java applications to handle errors appropriately. Exception handling is a very important yet often neglected aspect of writing robust Java applications. When an error occurs in a Java program it usually results in an exception being thrown. In this tutorial we will discuss what an exception is and how to handle it in java programming language.

What is an exception?

An exception (or an exceptional event) can be anything which interrupts the normal flow of execution of the program. When an Exception occurs, the normal flow of the program is disrupted and the program doesn’t continue further. In such cases we get a system generated error message. The good thing is that these exceptions can be handled in Java. Exception can occur at runtime (known as Runtime exceptions/unchecked exceptions) as well as at compile-time (known as Compile-time exceptions/checked exceptions).

Reasons for Exceptions:

There can be several reasons for an exception. Below are some of the reasons:

  • Trying to Opening a non-existing file – FileNotFoundException
  • The JVM has run out of memory – OutOfMemoryError
  • Invalid arithmetic operations e.g. Divide by zero – ArithmeticException
  • Operands being manipulated are out of range – ArrayIndexOutOfBoundsException

There are three categories of Exceptions you need to understand them to know how exception handling works in Java,

  1. Checked exceptions / Compile time exceptions
  2. Unchecked exceptions / Runtime Exceptions
  3. Errors

Checked exceptions:

A checked exception is an exception that occurs at the compile time, these are also called as compile time exceptions. These exceptions should be handled by the Programmer. If these exceptions are not handled in the program, it will give compilation error.

E.g. FileNotFoundException.

Consider the following program,

Try to compile the above program in command prompt, you will see the below error

FileNotFoundExpDemo.java:7: error: unreported exception

FileNotFoundException; must be caught or declared to be thrown

FileInputStream fi = new FileInputStream(file);

^

1 error

So the above program should include exception handling as below,

Unchecked exceptions:

Unchecked exception or Runtime Exception is an exception that is thrown during the time of execution of the program. The compilers do not check whether the programmer has handled them or not. These exceptions need not be included in any method’s throws list because compiler does not check to see if a method handles or throws these exceptions.

E.g. ArrayIndexOutOfBoundsException.

Consider the following program,

If you compile and run the above program you will see the below output,

a

b

c

d

e

“Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 5

at UncheckedExpDemo.main(UncheckedExpDemo.java:5)

Clearly it is evident that, it is the programmer mistake as the index range is not properly set. Also it should be noted that the message “Execution Continued” is not output because the program was terminated after the exception.

It can be handled as below,

Now see the output,

a

b

c

d

e

String Array is accessed out of its range

Execution Continued

You can see that the exception is handled and the execution is continued.

Errors

Errors indicate serious problems and abnormal conditions that arise beyond the control of the user or the programmer. Error defines problems that are not expected to be caught under normal circumstances by our program. Applications should not try to handle it.

Here is a simple program that can cause StackOverflowError.

Running the above program will throw below exception,

Exception in thread “main” java.lang.StackOverflowError

at ErrorJava.print(ErrorJava.java:6)

That is why we should be careful when using recursive function call. If there is no exit point, program will throw StackOverflowError.

Here is the hierarchy of the Exceptions that we discussed.

Exception handling

Exception hierarchy

Why to handle exception?

If an exception is thrown, which has not been handled by programmer then program execution can get terminated and system prints a non-user friendly error message.

E.g. Take a look at the below system generated exception,

Exception in thread “main” java.lang.NullPointerException

at ExceptionDemo.main(ExceptionDemo.java:4)

For an end user the above message won’t be easy to understand. In order to let them know that what went wrong we use exception handling in java program. We handle such conditions and then print a user friendly warning message to user, which lets them correct the error as most of the time exception occurs due to bad data provided by user.

Summary

  • Exception handling allows us to control the normal flow of the program when an exceptional event occurs.
  • It allows us to print a user friendly message.
  • Errors are abnormal conditions that should not be handled by the programmer.

Some of the Java interview Questions in Exception handling

  1. What is the super class of Exception and Error? (Ans: Throwable)
  2. What are checked and unchecked exceptions? Give an example?
  3. What is the difference between Error and Exception?
  4. What is the difference between throw and throws?
  5. Explain exception handling. How to create a custom exception? Whether custom exceptions are checked or unchecked?
  6. What is null pointer exception and what type it is? What is the best way to handle null pointer exception?
  7. Explain exception hierarchy.

 

The following two tabs change content below.
Working as a Java developer since 2010. Passionate about programming in Java. I am a part time blogger.

Add Comment

Required fields are marked *. Your email address will not be published.