Java Exception Handling with Examples

Errors occur naturally when we create and develop programs. Sometimes, we misspell a name or keyword, or sometimes we unknowingly change the symbols. These are very common and easy to handle errors. But programming is not that easy, and errors are not that simple.

So, to handle virtually any type of errors that may occur, language developers have created numerous ways to catch and prevent them. Java also supports a specific and well-defined mechanism of finding and preventing any errors. This mechanism is known as Exception Handling.

In this Java article, we will discuss exception handling in Java and different Exception Handling techniques.

 

Exception Handling In Java

Exception and Exception Handling in Java

The Exception refers to some unexpected or contradictory situation or an error that is unexpected. There may be some situations that occur during program development. These are the situations where the code-fragment does not work right.

Because it either accesses resources that do not exist or because it gets out of an unexpected range, etc. These anomalous types of situations are generally exceptions and the way to handle them is Exception Handling.\

There are two types of errors:

1. Compile-time errors in Java

Compile-time errors are the errors resulting from a violation of programming language’s grammar rules e.g., writing syntactically incorrect statements like

System.out.println “A Test”;

will result in a compile-type error because of invalid syntax. All syntax errors are reported during compilation.

2. Run-time errors in Java

Runtime errors occur during runtime or execution of the program because of unexpected situations. We use Exception handling routines of Java to handle such errors.

Some common examples of Exception are:

  • Divide by zero errors
  • Accessing the array elements beyond the range.
  • Invalid input
  • Hard disk crash
  • Opening a non-existent file
  • Heap memory exhausted

Types of Exceptions in Java

In Java, there are three types of Exceptions:

Types of Exceptions in Java

1. Checked Exceptions in Java

Checked Exception which is also called compile-time exceptions occurs at the compile time. If the method contains the code that throws a checked exception, the programmer must provide a mechanism to catch it in the same method.

Examples of Checked Exceptions are: IOException, SQLException, etc.

2. Unchecked Exceptions in Java

Java Unchecked Exception which is also called Runtime Exceptions occurs at runtime. This occurs during the execution of the program. It totally depends upon the developer to catch the runtime or unchecked exceptions.

Examples of Unchecked Exceptions are: ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc.

3. Error in Java

Error is not an exception but it is an issue that emerges out of the control of the user or the developer. We generally overlook the Errors in Java since we seldom take care of a mistake. For example, if there is stack overflow, there will be blunders.

Examples of errors are: VirtualMachineError, AssertionError etc.

User-defined or Customized Exception in Java

We all know that Java offers a rich set of in-built exception classes. But, there are some situations when there may be various application-specific errors. In such cases, We need to define our own exceptions to handle them.

Therefore, the users can create customized exceptions to serve this purpose. These are called the user-defined or customized exceptions.

Java Exception Methods

The Following list shows some important methods available in the Throwable class.

SN Method  Description
1 public String getMessage() It returns a detailed description of the occurred exception.
2 public Throwable getCause() Returns the cause of the occurred exception.
3 public String toString() Returns the result of the getMessage() method.
4 public void printStackTrace() Prints the result of the toString() method with the stack trace.
5 public StackTraceElement [] getStackTrace() Returns an array containing each element of the stack trace. 

Exception Handling in Java

Exception handling is a transparent way to handle program errors. As we studied, the process of dealing with the exception is called Exception Handling in Java.

It will help you to maintain the flow of execution and get the desired results. If JVM finds something unsatisfactory, then, it throws an exception.

For instance, consider the following code:

public class DivideByZero {
  public static void main(String args[]) {
    System.out.println(4 / 0); //This will cause Divide By Zero Exception
    System.out.println(“Please print me”);
  }
}

If we run the above program, the output message will be:

Exception in thread “main”
java.lang.ArithmeticException: / by zero
at DivideByZero.main(DivideByZero:java:3)

Advantages of Exception Handling in Java

The advantages of exception handling are:

  • Exception handling helps us to separate error-handling code from the normal code.
  • It clarifies the code by removing error-handling code from the mainline of the program
  • It enhances readability.
  • This stimulates consequences as the error-handling takes place in one place and in one manner.
  • It makes for clear, robust, fault-tolerant programs.

Exception Hierarchy in Java

All the Errors and Exceptions in Java are the subclasses of the ‘Throwable’ class, which itself is the superclass of the hierarchy. One branch is the Error and the other is Exception. The exception is again divided into checked and unchecked exceptions.

ArithmeticException is an example of an Exception while StackOverflowError is an example of Error.

The below figure shows the exception hierarchy in Java:

 

exception hierarchy in java

The ‘try’ block

The try block in Java contains the statements where there is a chance of exception. A catch block always follows the try block.This catch block handles the exception that occurs in the associated try block. There should be a catch block or a finally block after a try block.

Syntax of try block

try
{
//statements causing an exception
}

While writing a program, if you think that certain statements in a program can throw a exception, enclosed them in try block and handle that exception

The ‘catch’ block

A catch block is a block where we can handle the exceptions. The catch block must always follow the try block. There can be multiple catch blocks in a try block.

Syntax of try catch in Java

try
{
     //statements that may cause an exception
}
catch (Exception e)‏
{
     //error handling code
}

Catching Exceptions in Java

In Java, we use a combination of a try-catch block to catch or handle an exception. We generally place the try-catch block around the code that can generate an error. The code inside the try-catch is the protected code.

We can add a number of catch blocks for various exceptions. The syntax of the try-catch block is as follows:

try
{
// Protected code
}
catch (ExceptionName e1)
{
//Catch block
}
catch (ExceptionName e2)
{
//Catch block
}

The code that can generate error is placed in the try block. When an exception occurs in a try block, the catch block associated with that try block handles that exception. After every try block, there must be either by a catch block or finally block.

A catch statement declares the type of exception that we try to catch. If there is an exception in the try block, then the compiler checks for the catch block. If that type of exception is listed in a catch block, it passes the exception to the catch block as an argument.

Example:

package com.techvidvan.exceptionhandling;
public class TryCatchDemo {
  public static void main(String args[]) {
    try {
      int myArray[] = new int[10];
      System.out.println("Accessing the fifth element of array: " + myArrray[5]);
    }
    catch(ArrayIndexOutOfBoundsException exception) {
      System.out.println("Exception thrown:" + exception);
    }
    System.out.println("Out of the try-catch block.");
  }
}

Output:

Accessing the fifth element of the array: 0
Out of the try-catch block.

Multiple Catch Blocks in Java

We can place multiple catch blocks after a try block in Java. If there are multiple exception classes in the try block, then Java allows several catch blocks to handle them.

The syntax of multiple catch block is as follows:

try
{
//protected code
}
catch (ExceptionType1 exception1)
{
//Catch block1
}
catch (ExceptionType2 exception2)
{
//Catch block2
}
catch (ExceptionType3 exception3)
{
 	//Catch block3
}

The above syntax shows three catch blocks, but there can be as many catch blocks as we want after a single try block. If there occurs an exception in the try block, then the exception is thrown to the first catch block in the list. If ExceptionType1 matches the datatype of the thrown exception, it gets into that catch block.

But if it does not match, then the exception passes down to the second catch statement and so on. This will continue until the exception either goes into any catch block or falls through all catch statements.

Code to explain multiple catch blocks in Java:

package com.techvidvan.exceptionhandling;
public class MultipleCatchBlockDemo {
  public static void main(String[] args) {
    try {
      int array[] = new int[5];
      array[5] = 30 / 0;
      System.out.println(a[8]);
    }
    catch(ArithmeticException e) {
      System.out.println("Arithmetic Exception");
    }
    catch(ArrayIndexOutOfBoundsException e) {
      System.out.println("ArrayIndexOutOfBounds");
    }
    catch(Exception e) {
      System.out.println("Parent Exception");
    }
    System.out.println("Rest code");
  }
}

Output:

Arithmetic Exception
Rest code

The Throws Keyword in Java

If a method invokes code that causes an exception, then the method should provide a catch clause to handle the exception. If a catch block is unable to handle the exception, then the exception passes out of the method. After that, the code calling that method handles this exception.

If an exception is allowed to pass through a method, a throws clause is required in the method declaration. It indicates that an exception can occur that the method itself does not handle. It is specified with the method header.

For example:

public static void main(String args[]) throws Exception
{
  //code
}

This indicates that if an exception occurs, it will automatically report to the error handler or the processor

We can also declare multiple exceptions in the throws clause. For example,

public static void main(String args[]) throws NumberFormatException, IOException
{
  //code
}

The Throw keyword

We can also throw an exception, either a newly instantiated one or an exception that we just caught, by using the throw keyword. A throw statement causes the current method to immediately stop executing.

It is much like a return statement, and the exception is thrown to the previous method on the call stack.

For example, the following statement throws a new ArrayIndexOutOfBoundsException, with five as an invalid index:

throw new ArrayIndexOutOfBoundsException(5);

Difference between throws and throw keywords

Let us now try to understand the difference between throws and throw keywords. The throws keyword postpones the handling of a checked exception while the throw keyword invokes an exception explicitly.

Example of throw keyword:

package com.techvidvan.exceptionhandling;
public class ThrowKeywordDemo {
  void checkAge(int age) {
    if (age < 18) throw new ArithmeticException("Not Eligible for voting");
    else System.out.println("Eligible for voting");
  }
  public static void main(String args[]) {
    ThrowKeywordDemo obj = new ThrowKeywordDemo();
    obj.checkAge(25);
    System.out.println("End Of Program");
  }
}

Output:

Exception in thread “main” java.lang.ArithmeticException:
Not Eligible for voting
at ThrowKeywordDemo.checkAge(ThrowKeywordDemo.java:6)
at ThrowKeywordDemo.main(ThrowKeywordDemo.java:14)

Example of throws keyword:

package com.techvidvan.exceptionhandling;
public class ThrowsKeywordDemo {
  int division(int num1, int num2) throws ArithmeticException {
    int result = num1 / num2;
    return result;
  }
  public static void main(String args[]) {
    ThrowKeywordDemo obj = new ThrowKeywordDemo();
    try {
      System.out.println(obj.division(18, 0));
    }
    catch(ArithmeticException ae) {
      System.out.println("You cannot divide a number by zero");
    }
  }
}

Output:

You should not divide a number by zero

The finally Block in Java

Java finally block is the block of code which always executes whether or not the exception occurs. This allows us to run any statement that we want to get executed no matter what happens to the code inside the try block.

The syntax of the finally block is:

try
{
//Protected code
}
catch (ExceptionType1 et1)
{
//Catch block
}
catch (ExceptionType2 et2)
{
//Catch block
}
finally
{
//The finally block always executes.
}

Example of the finally block in Java:

package com.techvidvan.exceptionhandling;
public class FinallyBlockDemo {
  public static void main(String args[]) {
    int num[] = new int[10];
    try {
      System.out.println("Accessing the fifth element of the array:" + num[5]);
    }
    catch(ArrayIndexOutOfBoundsException e) {
      System.out.println("Exception thrown:" + e);
    }
    finally {
      num[2] = 6;
      System.out.println("The value of the third element of the array  is: " + num[0]);
      System.out.println("The finally always executes");
    }
  }
}

Output:

Accessing the third element of the array: 0
The value of the first element of the array is: 6
The finally block always executes.

Conclusion

In this article, we discussed the Exception handling in Java and its various ways with examples. We also learned the important statements necessary for exception handling like-try, catch, throw, throws, and finally.

We hope now you must be able to check and handle the unwanted errors in your programs.