Exceptions in Java

What is an Exception?

exception is an abnormal condition or error which may arise while the code is running. To be more precise, Exception is runtime error.

Now these kind of exceptions can happen for many reasons.

For example :

  • Dividing a number by zero.
  • Trying to read a file which doesn’t exist.
  • Trying to insert data in an index of array which does not exist.
  • The memory of JVM is out of memory.

And this list goes on ? …
Some of these errors can happen for the fault of coding pattern, and some can happen totally because of JVM. But, we can handle these errors using Exception in Java.

Types of Exceptions

Exceptions can be of 2 types :

  • Checked Exception
  • Unchecked Exception
  • Checked Exceptions : Checked Exceptions are those which can be found during the compilation are called the checked exceptions. Example – ClassNotFoundException, NoSuchMethodException etc.
  • Unchecked Exceptions : Unchecked Exceptions are those which can be found in the runtime. For example: NullPointerException, IndexOutOfBoundException etc.

Syntax for Exception in Java

There are 5 main keywords in Exceptions.

  • try
  • catch
  • finally
  • throw
  • throws

Now, let us see what the uses for these keywords in Java are. The simplest way to handle an exception is using a try-catch block.

try and catch blocks :

public class ExceptionDemo {
	public static void main(String[] args) {
		int a = 0;
		
		/*try block starts*/
		Try
                {
			int division = 12/a; 
			System.out.println("No error in Try block");
		}
		/*try block ends*/
		
		/*catch block starts*/
		catch(Exception e)
		{
			System.out.println("The error is : \n"+ e);
		}
		/*catch block ends*/
	}
}

 

“try” block is something where we write the block of code which may cause an issue while running or the block which we want to monitor.

“catch” block is for catching the error which try block can throw while the execution.

In the above code, Catch block has an argument for Exception and we have printed the cause of exception in the console.

Please note that, Exception is the superclass of all the exception classes and we will discuss about the Exception class and all the subclasses later.
You may wonder why the above code doesn’t provide any error message while compilation. But proper answer is, when we compile, the compiler checks if there is any syntax error in the code.

It doesn’t check for semantic error in the code or the values assigned in the variables. When we compile the above code, the compiler doesn’t bother to analyze that the value of variable a before division is 0.

So, when we run the above code, we get an exception as we are trying to divide some integer by zero.

We have 2 statements in try block, why the first statement executed and the second was not?

Well, the answer is: As soon as the JVM encounters an error in the try block, it will pass the control flow of the code to the catch block and it will not execute the rest of the try block anymore.

What will be the output if we don’t use any try/catch block for the above code?

Let’s write the code again!

public class ExceptionDemo {

	public static void main(String[] args) {
		int a = 0;
		int division = 12/0;
		System.out.println("No Error!");
	}

}

The output will be :

Exception in thread "main" java.lang.ArithmeticException: / by zero

       at com.src.exception.ExceptionDemo.main(ExceptionDemo.java:7)

finally block:

“finally”

block is a block in which we want to write a code which we want to execute in any condition (doesn’t matter if there was an error thrown from try block or not).

This block will execute right after the try block ends.

public class ExceptionDemo {

	public static void main(String[] args) {
		int a = 0;
		/*try block starts*/
		Try
                {
			int division = 12/a;
			System.out.println("No error in Try block");
		}
		/*try block ends*/
		
		/*catch block starts*/
		catch(Exception e)
		{
			System.out.println("The error is : \n"+ e);
		}
		/*catch block ends*/
		
		/*finally block starts*/
		finally{
			System.out.println("I am in Finally block");
		}
		/*finally block ends*/
	}

}

For the above piece of code, after the execution of the try block, it handles the exception thrown by the try block and then executes the finally block. The output will be:

The error is:

java.lang.ArithmeticException: / by zero

I am in Finally block

Note:

  • “catch” block cannot be written without a “try” block.
  • “try” block must be accompanied by either a “catch” block or a “finally” block or both the blocks.
  • “finally” block must be accompanied by a “try” block.


Exception Class

Exception Class is the superclass of all the other exception Classes. We can describe it graphically:

But, let us discuss the structure of the exception handling framework in Java.

Though Exception class is superclass of all exception classes, it is a subclass of Throwable Class. Throwable class is also the superclass is Error Class.

Error class mainly deals with the severe problems that are associated with the JVM in runtime. One main kind of exception in RuntimeException which is a direct subclass of Exception Class.

All those kind of exception classes which are children of RuntimeException class are Unchecked Exceptions.

Others are Checked Exception (We already discussed the definitions of Checked and Unchecked Exceptions previously).

So, let us redraw the whole structure again of the whole Exception Handling Framework.

For the list of all the exceptions in Java, please refer to the Oracle Documentation for Exception Handling Framework

Multiple Catch Blocks

Java supports multiple catch blocks. If we are not sure which kind of exceptions are going to be thrown from the try block, we can add multiple exception blocks there.

But, there is particular rule for that. We must write the child exception class first and then the parent exception classes later. We can consider the following code below.

What is use for Multiple Catch Blocks ?

We know that Exception class is the super class of all other exception classes and that means Exception class is able to handle all the possible exceptions in Java.

Then why we need any other exception classes? The answer is, there can be some scenario when we need to trigger different actions depending on the type of exception occurred.

If we can catch the specific type of exception, then it is easier for us, isn’t it?

“throw” Statement

Java not only Supports the users to catch the system thrown exceptions. We can even throw exceptions on our own. Here is the example for it!

public class ExceptionDemo {

    public static void main(String[] args) {
	   int a = 0;
	   try 
           {
		 throw new ArithmeticException();
	   }
		
	   catch(ArithmeticException e)
	   {
		System.out.println("Caught Arithmetic Exception");
	   }

    }

}

Here, intentionally we have thrown an exception new ArithmeticException from the try block and then we have caught in the catch block. The output of the program will be :

Caught Arithmetic Exception

We can actually throw any instance of the throwable objects.

“throws” statement

It is possible that a method can create an exception , but we do not want that method to handle that exception. But, we should mention that in the method name.

 

public class ExceptionDemo {

	public static void main(String[] args) {
		try 
                {
			new ExceptionDemo().callExceptionMethod();
		} 
                catch (Exception e) 
                {
                      System.out.println("Caught Exception from method 
                      callExceptionMethod()");
		}
	}

	private void callExceptionMethod() throws ArithmeticException {
		int a = 5, b = 0;
		int c = a / b;
		System.out.println(c);
	}

    }

 

Output :

Caught Exception from method callExceptionMethod()

In the above code, main method is calling callExceptionMethod() which will throw a ArithmeticException, but we don’t want this method to handle this exception.

Instead, we wanted the main method to handle this exception. So, we added “throws ArithmeticException” in the method and now the caller method will have to handle the exception.

Creating your own Exception Class

It may be helpful sometimes to create our own class to classify special type of situation that are present in some application. It sounds big!... but, it isn’t.

Here is the process for creating a completely customized exception.

We are creating a customized exception class MyException. This class will extend Exception class and we will add some method to it, which will make it unique. Here is the class Now, we will be using this exception class:

class MyException extends Exception {
	String getMessageForMyException()
	{
		return "I have created mine own Exception";
	}
}
public class ExceptionDemo {

	public static void main(String[] args) {
		try
                {
			throw new MyException();
		}
		catch(MyException e)
		{
			System.out.println(e.getMessageForMyException());
		}
	}
}

The output will be :

I have created mine own Exception


Next > < Prev
Scroll to Top