Why Exception Handling in Java?

Pasan Kamburugamuwa
7 min readOct 22, 2021

--

In every program, whether you build it using java or any other language, there may be errors that might occur at runtime. Here, we will go through the java exception handling with some examples.

Java’s exception-handling mechanism is a clean, well-lighted way to handle “exceptional situations” that pop at runtime. It lets you put all your error-handling code in one easy-to-read place. It’s based on you knowing that the method you’re calling is risky (a method may be having errors in the runtime environments and this will lead to terminating the running instance of the program) so that you can write code to deal with that possibility. If you might get an exception when you call a particular method, you can be prepared for the possibility of recovering from the error that caused the exception.

What is an exception?

According to the dictionary, we can define the exception as an abnormal condition. In programming, the exception is an unwanted or unexpected event that occurs during the execution of the program.

Hierarchy of Java Exceptions

According to Oracle, there are three kinds of java exceptions and they are mentioned below.

  1. Checked Exception

2. Unchecked Exception

3. Error

So let’s have a look at each of them,

Checked Exception

The classes that are directly inherited from the Throwable class are called the checked exception. But in checked exception, Runtime exception and error are not considered. Checked exceptions are taken into consideration at compile time.

Unchecked Exception

The classes that are inherited from RuntimeException are called unchecked exceptions. So in here, the code is not checking at the compile-time, instead of, it checks at the runtime of the program.

Error

Errors in the java programs are irrecoverable. Some examples errors are OutOfMemoryError, VirtualMachineError etc.

The compiler checks for everything except RuntimeExceptions.

Let’s look at the keywords which are used in the java exception.

  1. try — This is used to specify a block where we should place an exception code. You need to have caught or finally after the try block.
  2. catch — This is used to handle the exception in java and this also contains a block.
  3. finally — execute the necessary code of the program.
  4. throw — Used to throw an exception
  5. throws — Used to declare exceptions. This specifies that there may occur an exception in the method. This always uses a method signature.

Flow control in try/catch blocks

When you call a risky method, one of two things can happen as the risky method either succeeds and the try block completes, or the risky method throws an exception back to your calling method.

How the try/catch block works in java program — Image is taken from Head First Java by Kathy Sierra

Things to remember when using the try/catch blocks.

  1. If the try block fails due to an exception, flow control immediately moves to the catch block. When the catch block completes, the finally block runs. When the finally block completes, the rest of the method continues on.
  2. If the try block succeeds with no exception, flow control skips over the catch block and moves to the finally block. When the finally block completes, the rest of the method continues on.
  3. If the try or catch block has a return statement, finally will still run! Flow jumps to the finally, then back to the return.

So let’s have a simple example of java exception handling.

public class Main{
public static void main(String args[]){
try{
int data=20/0; //the code that have an arithmatic exception
}catch(ArithmeticException e){
e.printStackTrace(); //print the error in here
}
System.out.println("Other methods will be executed normally");
}
}

Why do we need to throw exceptions?

In Java, we can create our own custom exceptions making the code recovery and debugging easier.

Java throw keyword is used to throw an exception explicitly.

Throwing Unchecked Exception

We can define our own set of conditions and throw an exception using the throw keyword. Let’s have an example of throwing the ArithmaticException.

package com.example;

public class Main{
public static void main(String[] args){
validateStudent(23);
}
public static void validateStudent(int age) {
if(age>15) {
//this will throw an arithmatic exception is the person's age is greater than 15
throw new ArithmeticException("Person is not an student");
}
else {
System.out.println("Person is a student");
}
}
}

This code segment throws an unchecked exception. The output of the above code segment will be as below.

Throwing Checked Exception

If you are using checked exception using throw keyword, it must or handle exception using catch block or the method must declare using a throws declaration.

package com.example;

import java.io.FileInputStream;
import java.io.IOException;

public class Main{
public static void main(String args[]) throws IOException
{
FileInputStream fis = null;
fis = new FileInputStream("D:/file.txt");
int k;

while(( k = fis.read() ) != -1)
{
System.out.print((char)k);
}
fis.close();
}
}

Every subclass of Error and RuntimeException is an unchecked exception in Java. A checked exception is everything else under the Throwable class.

After running the above code segment, we will get an output like below.

Throwing User-defined Exception

User-Defined Exception or custom exception is creating your own exception class and throwing that exception using the ‘throw’ keyword. This can be done by extending the class Exception.

package com.example;

import java.io.IOException;

public class Main{
public static void main(String args[]) throws IOException
{
try{
throw new MyExceptionClass(1); // this is used to throw the exception
}
catch(MyExceptionClass e){
System.out.println(e) ;
}
}
}

class MyExceptionClass extends Exception{
int a;
MyExceptionClass(int b) {
a = b;
}
public String toString(){
return ("Exception Number = "+a) ;
}
}

So in the above program, the MyExceptionClass is the user-defined exception and it is based on the Exception class. After the exception class is called, there is the catch clause, the relevant output (exception) will be displayed.

Finally: for the things you want to do no matter what.

A finally block is where you put code that must run regardless of an exception.

package com.example;

public class Main{
public static void main(String args[])
{
try{
int a = 100;
int b = a/0;
}catch (Exception e){
e.printStackTrace();
}finally {
System.out.println("This will print no matter what happen in try/catch block");
}
}
}

A finally block lets you put all your important cleanup code in one place instead of duplicating it. As from the above program, the things in the final block will be executed with no consideration within the try/catch block. The result is given below.

Methods can throw multiple exceptions.

A method can throw multiple exceptions if it dam well needs to. But a method’s declaration must declare all the checked exceptions it can throw (although if two or more exceptions have a common superc1ass, the method can declare just the superclass)

Catching multiple exceptions in java — Example is taken from Head First Java by kathy sierra

You can’t put bigger baskets above small baskets.

Catch blocks are not like overloaded methods where the best match is picked. With catch blocks, the JVM simply starts at the first one and works its way down until it finds a catch that’s broad enough (in other words, high enough on the inheritance tree) to handle the exception. your first catch block is catch (Exception ex). the compiler knows there’s no point in adding another-they’ll never be reached.

The only thing different from overloading is a readability requirement that subclasses appear before its superclass.

package com.example;

public class Main{
public static void main(String args[])
{
try{
int a = 100;
int b = a/0;
}catch (ArithmeticException e){
e.printStackTrace();
System.out.println("Inside the arithmatic(subclass) catch block");
}catch (Exception e){
e.printStackTrace();
System.out.println("Inside the exception(parent) catch block");
}
}
}

So in the above program, the ArithmaticException which is a subclass of Exception appears first and it will compile okay. But if you change the two catch blocks by having Exception class in the first catch block, there will be a compile-time error. The output of the above program is given below.

Summary

A method can throw an exception when something fails at runtime.

An exception is always an object of type Exception. (Which, as you remember from the polymorphism chapters means the object is from a class that has Exception somewhere up its inheritance tree.)

The compiler does NOT pay attention to exceptions that are of type RuntlmeException. ARuntimeExceplion does not have to be declared or wrapped in a try/catch (although you’re free to do either or both of those things)

A method throws an exception with the keyword throw, followed by a new exception object.

So in this article, we have discussed a wide area of java programming that is much needed for developing your application. Exception handling is a key area of developing an application as every program runs into errors and it affects the free-flowing of the program and the sudden crash of the system. To avoid this, we need to understand in which instance, there might be exceptions happening and need to fix those. Hope you understand why and how we handling the exceptions in java. See you in the next tutorial. Until then bye.

--

--