Exception Handling Program in Java | Example Code and Interview Questions

Exception Handling Program in Java | Example Code and Interview Questions

EXCEPTION HANDLING is a very important concept in Java. While working on any Java project, many times you have to deal with it.

In this complete tutorial, you will learn about Exception Handling using Java programming examples. It will also help you to prepare for exception handling in java interview questions.

What is Exception Handling in Java?

We generally don’t like to deal with exceptions or errors when it comes to programming, but Java provides us with a great way to handle exceptions that are easy to understand and straightforward in use.

Exception Handling is the dominant mechanism to handle runtime breakdown. To prevent unexpected termination of the program, exceptions must be handled. The term exception means an exceptional state that may occur during the implementation of the program.

The core use of exception handling is to let the program execute in a normal way.

Example:

Let us consider a set of 10 statements. Assume that an exception occurs at statement 7; thereby terminating the program execution from statement 7, i.e., statement 7-10 will not be executed.

HIERARCHY OF EXCEPTIONS in Java:

All the exceptions in Java are the subclass of the Throwable class.

  • Exception class is for the conditions that are exceptional and the program should catch such exceptions.
  • RuntimeException class is a subclass of the Exception class. Exceptions under this class are by design described for programs.
  • Error class is used by the Java run-time system to point out errors having to do with the run-time environment, itself. OutOfMemoryError is an example of such an error.

What are the different TYPES OF EXCEPTION?

Exception Handling in Java defines 3 types of Exceptions, namely –

  • Checked Exceptions
  • Unchecked Exceptions
  • Errors

Let us have a look at what these types of exceptions actually mean.

Read it carefully. You can found many of exception handling in java interview questions from these types.

1. CHECKED EXCEPTIONS:

An exception that is predicted by the programmer is known as a checked exception. This exception occurs at compile time and can be handled or such exceptions can be thrown using the throws keyword.

For example:

Consider a Java program which tries to open a file at location “C:\check\xyz.txt” and prints the text of it. The program doesn’t compile, because the function main() uses FileReader() and FileReader() throws a checked exception FileNotFoundException.

2. UNCHECKED EXCEPTIONS:

Exceptions that are not identified at compile time and occur at the time of execution is known as unchecked exceptions. Such exceptions are also called as run time exceptions.

For example:

Exceptions that fall under the hierarchy of RuntimeException are all considered as unchecked exceptions.

3. ERRORS:

Errors are exceptional cases that are out of the scope of application and it’s not possible to foresee and recover from them.

For example:

Hardware failure, out of memory error. Some of the common Errors are OutOfMemoryError and StackOverflowError.

KEYWORDS IN EXCEPTION HANDLING:

Java provides specific keywords for exception handling purposes. There are 5 keywords that are used for handling exceptions, namely –

  • try: it is used to enclose the code that may throw an exception. The try block should always be inside the method.
  • catch: it is used to handle the exception. This block is always written down after the try block.
  • finally: it is used to execute the code which is of high significance. No matter what, if the finally block is written, it is always executed. This block is written either after try block or catch block.
  • throw: keyword is used to externally throw an exception. It throws either checked or unchecked or customized exceptions
  • throws: keyword is used to declare the exceptions so that the programmer is aware that an exception will occur.

Exception Handling Java Code Example

Understanding different try-catch blocks with the programs will help you for interview preparation as well.

THE try-catch BLOCK in Java:

The basic syntax of the try-catch block is as follows:

Basic Syntax:

try{
  //code that may possibly throw an exception
} catch(exception_class){ }

Coding Example:

class Example{
  public static void main(String args[]){
    int x,y,z;
    try{
      x = 5;
      y = 0;
      z = x / y;
      System.out.println("The output for z cannot be executed.")
    }
    catch(ArithmeticException e)
    {
      System.out.println("Expression throws divide by 0 exceptions");
    }
  }
}

Output:

Expression throws divide by 0 exception

Here, in the above program, we are trying to divide x by 0 which throws an exception and thus the code is enclosed in the try block. Therefore, the catch block handles this exception and prints Expression throws a divide by 0 exceptions.

MULTIPLE catch BLOCKS in Java:

The basic syntax of try block with multiple catch block is as follows:

try {
  // code that throws an exception
} 
catch (exception_class1 e1) {
  // handle the exception
} 
catch (exception_class2 e2) {
  // handle the exception
} 
catch (exception_class3 e3) {
  // handle the exception
}

There are few general rules that must be kept in mind while using try block with multiple catch blocks:

  • At a time only one exception occurs and only one catch block is executed.
  • The multiple catch blocks must be ordered from most specific to most general.

Coding Example:

class MultiCatch{
  public static void main(String args[]){
    try{
      int a[] = new int a[];
      a[6] = 15/0;
    }
    catch(ArithmeticException e){
        System.out.println("Arithmetic Exception Handled");
    }
    catch(ArrayIndexOutOfBoundException e1)
    {
        System.out.println("Array index out of bound!");
    }
  }
}

Output:

Arithmetic Exception Handled

Here, this is a different situation where both ArrayIndexOutOfBoundsException and ArithmeticException occurs. Since the first catch is Arithmetic Exception, it will be caught there. And the program control will be continued after the catch block.

NESTED TRY BLOCK in Java:

A nested try block is used when one block of code a different kind of error while the other block is based on a different exception. In case if inner try block does not contain a catch handler for a respective exception then the outer try-catch block is verified for a match.

class NestedException
{
  public static void main(String[] args) {
    try {
      int arr[]={7,0,12,8};
      try {
        int x=arr[2]/arr[1];
      }
      catch(ArithmeticException e) {
        System.out.println("Divide by Zero Exception");
      }
      arr[4]=3;
    }
    catch(ArrayIndexOutOfBoundsException e1) {
      System.out.println("Array index is out of bound");
    }
  }
}

Output:

Divide by Zero Exception
Array index is out of bound

throw and throws keyword in Java:

The syntax of throw keyword in Java is as follows:

throw exception_name;

Coding Example:

In the below example, we are using if- control statement.

We will create a method to check if the number is less than 0 or not. If the number is less than 0, then we throw ArithmeticException, otherwise, we print division is possible.

public class ThrowExample
{
  void validate(int number) {
    if(number <= 0){
      throw new ArithmeticException("Invalid Input");
    }
    else {
      System.out.println("Division is possible.");
    }
  }
  public static void main(String args[]) {
    validate(0);
    System.out.println("Execution is possible for remaining code");
  }
}

Output:

Exception in thread main java.lang.ArithmeticException: Invalid Input

Now, let us understand the concept of throws keyword.

First let’s check the basic syntax of throws keyword, which is as follows:

return_type method_name() throws exception_name;

Coding Example:

class ThrowsExample
{
 void check()throws ArithmeticException
 {
   throw new ArithmeticException("An arithmetic exception thrown");
 }
 public static void main(String args[])throws ArithmeticException
 {
   ThrowsExample obj=new ThrowsExample();
   obj.check();
   System.out.println("Program executed");
 }
}

Output:

An arithmetic exception thrown
Program executed

Here, in the above example, an exception is declared but not handled. If in such exception occurs, then at run time the exception would be thrown but not handled while if there occurs no exception then the n code executes normally.

To avoid such cases, one can use the try-catch block to handle the exception that is thrown.

finally block in Java:

As we have learned earlier, the finally consists of statements that must be executed at any cost, whether the exception occurs or not. The finally block can be written either after the try-catch block or can be directly followed after the try block.

The basic syntax of the finally block is as follows:

try
{
  //code that may possibly throw an exception
}
catch(exception_class)
{
  //handle the exception thrown
}
finally
{
  //statements to be executed
}

Coding Example:

A simple example of the finally block is shown below:

class Example{
public static void main(String args[]){
  int x,y,z;
  try {
    x = 5;
    y = 0;
    z = x / y;
    System.out.println("The output for z cannot be executed.")
    }
    catch(ArithmeticException e)
    {
    System.out.println("Expression throws divide by 0 exception");
    }
    finally
    {
    System.out.println(“You are in the finally block”);
    }
  }
}

Output:

Exception throws divide by 0 exception
You are in the finally block

Custom Exceptions in Java:

So far, we have seen that there are in-built pre-defined classes that define exceptions in Java. Java also gives the provision to its users to define exceptions on their own and throw them using the throw keyword. Such exceptions are called user-defined or custom exceptions.

Let us have a look at how this can be done with the help of an example.

Coding Example:

class MyNewException extends Exception
{
 String s1;

 MyNewException(String s2) {
  s1=s2;
 }
 public String toString() {
  return ("MyNewException defines: "+s1) ;
 }
 public static void main(String args[]){
  try {
   throw new MyNewException("E – R – R – O - R ");
  }
  catch(MyNewException e1) {
   System.out.println(e1) ;
  }
 }
}

Output:

E – R – R – O – R

That’s all about exception handling. Practice and try a few examples of programs that need exception handling.

This also covers exception handling in java interview questions. If you have any question for me, please write in the comment section below.

Happy Learning!

2 Comments

  1. Thanks, Aniruddha for sharing. Kudos to the author Pranati for writing it in detail.

    I will share it in my Java class.

  2. int a[] = new int a[]; — This is not correct. If you declare array of int, you should specify size in this case. So the correct one is
    int a [] = new int[6];

Leave a Reply

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