Exception Handling in java

The Exception Handling in Java is a simple powerful trick to handle the runtime errors. Exception is an object which is thrown at runtime. It sabotages the normal flow of program. After exception handling, you can maintain normal flow of your program.

Advantage of Exception Handling

Exception sabotages the normal flow of program. That’s why we need handling. The main advantage of exception handling is to maintain the normal flow of the program.

Assume there is a program as below.

An exception occur at the 5th line of this program. Due to this exception you will get an exception error as below,

You can also see the rest of the code will not be executed. But if we do exception handling the rest of the code will be executed. That’s why we should use exception handling.

Type of Java Exceptions

There are mainly three types of exceptions.

Error is also considered as the unchecked exception. Let’s understand the difference among these three types

Exception handling is mainly used for handle checked exceptions. If any unchecked exception occurred in the program, such as ArrayIndexOutOfBoundsException, it is programmer’s fault, as he didn’t check the program before use. Moreover if any error occurred it is out of programmer’s control.

Difference among Checked Exception, Unchecked Exception and Error

Checked Exception : The directly inherit Throwable classes except Runtime Exception and Error are called checked exceptions. Checked exceptions are checked at compile-time. (Eg :- IOException, SQLException, ClassNotFoundException)

Unchecked Exception : Classes that inherit Runtime Exception are called unchecked exceptions. Unchecked exceptions are checked at runtime. (Eg :-ArithmeticException, NullPointerException, NumberFormatException etc.)

Error : Error is irrecoverable (Eg:- StackOverflowError, OutOfMemoryError)

Hierarchy of Java Exception classes

Root class is Throwable class and it inherited by two subclasses which are Exception and Error.

Keywords in Exception Handling

There are 5 keywords in Exception Handling. Those are try, catch, finally, throw and throws.

Lets consider one by one.

try block

We use the keyword “try” to specify where to place the exception code. It must be used within the method and must be followed by either catch or finally.

try-catch block Syntax

try-finally block Syntax

N.B : The rest of the block code will not work if an exception is occurred in the some statement of try block. So keep in mind that code, which is no exception, should not be kept in a try block.

catch block

We used catch block to handle the Exception. in catch block within the parameter should declaring the type of exception. It must be the parent class exception or the generated exception type. The catch block only use after a try block and we can use any number of catch blocks under one single try block.

Let’s consider an example in try-catch block

Remind previous example.

In here we got an error which “ Exception in thread “main” java.lang.ArithmeticException: / by zero at Calculations.main(Calculations.java:5)”

Let’s see, how can we handle this exception.

Output :

The print statement at line 8 which is under try block, not to be seen in the output. Because at line 7, an exception is occurred. So rest of the try block will not be executed.

Here we use generated exception type to handle exception. And also we can use parent class exception easily by adding “Exception” word instead of “ArithmeticException” word at line 10.

We can resolve the exception in a catch block.

If there any code that occurs exception error in the catch block, the catch block will not handle the exception.

And also if you use different exception type to handle generated exception, it will not handle the exception.

Multiple-catch block

A single try block can have more than one catch block and each catch block must have a different exception handler.

There can have multi catch blocks but at a time only one exception occurs and only one catch block is executed.

All catch blocks under one try block must be ordered from most specific to most general.

Let’s see an example,

Output :

Here we can see two exception but at a time one exception occurred and it corresponding catch block is executed.

Assume there are ArithmeticException in try block. But you can see there is no corresponding Exception type. In such case the Parent Exception class which “Exception” contained catch block will executed.

And also remember if you try to handle the exception without considering the order of exceptions which from most specific to general, you will definitely get a compile time error.

Nested try block

In some program part of the block will occurred one exception and entire block will occurred an another exception. In that case we use nested try blocks. Simply Nested try block is a try block within a try block.

Output :

finally block

This block is used to execute the important code of the program. Whether an exception is handled or not, the finally block will execute. finally block must under try block or catch block.

If exception not occurred or exception occurred or occurred exception handled or not handled, under any circumstances the finally block will execute.

A try block can have only one finally block.

If program exits the finally block doesn’t execute.


throw keyword

This keyword is used to throw an exception. By using throw keyword can throw either checked or unchecked exceptions. Throw keyword mostly used for throw custom exceptions.

Output :

Exception propagation in Java

An exception is first thrown from the top of the stack and if it is not caught, it drops down the call stack to the previous method, if not caught there, the exception again drops down to the previous method, and so on until it caught or until it reach the very bottom of the call stack. This is called exception propagation.

Unchecked exceptions are forwarded in calling chain and checked exceptions are not forwarded in calling chain.

Let’s see an example of Unchecked Exceptions Propagation,

Output :

In this program you can see an exception occurs at method3. But it is not handle at method3. So it propagated to previous method2.It is not handled in there also. Therefore it is propagated to previous method which is also not handled the exception. Finally it propagated to main method and in here exception is handled.

Remember this, exception can be handle in any method of call stack, can handle either in main(), method1(), method2() or method3().

throws keyword

This keyword is used to declare an exception. It points out specifies that may occur an exception in the method. It never throw exceptions.

Syntax of throws

Under this it only declare checked exceptions. Because unchecked exception are under programmer control, it should be correct by programmer and error beyond the programmer’s control.

The main advantage of throws keyword using is Checked Exception can be propagated.

There are two types,
1. You caught the exception.
2. You declare the exception.

Let’s see example for each type,

You caught the exception (Handle the exception using try/catch)

Output :

You declare the exception (Specifying throws with the method)

In here, if exception does not occur, the code will be executed fine.
But if any exception occurs, an exception will be thrown at runtime because throws do not handle the exception.

If exception does not occur,

Output :

If exception occurs,

Output :

Difference between throw and throws in Java

Difference among final, finally and finalize




Exception Handling with Method Overriding in Java

When we talk about method overriding with an exception handling we must remember mainly two rules.

If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception,

Output :

But it can declare unchecked exception,

Output :

2. If the superclass method declares an exception, subclass overridden method can declare same, subclass exception or no exception but it cannot be declare as parent exception.

Subclass overridden method declares parent exception,

Output :

Subclass overridden method declares same exception,

Output :

Subclass overridden method declares subclass exception,

Output :

Subclass overridden method declares no exception,

Output :

Custom Exception in Java

In programing sometimes we need our own exception. That’ why we need custom exception. If you are creating your own Exception that is known as custom exception or user-defined exception. Custom exceptions, customize the exception according to user need.

Let’s se some examples,

Output :

This is all about Exception Handling in Java. I think this will help you to get a good knowledge about Exception Handling in Java in an easy way.

Undergraduate student of University of Colombo School of Computing

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store