Java Exception – Learn with its Types, Methods & Examples

When you create and develop programs, errors occur naturally. Sometimes, you misspell a variable name or a keyword, or sometimes there is a network connection problem, etc.

These errors are very common and easy to handle errors and are known as Exception. To handle these exceptions, Java provides numerous ways to catch and prevent them.

Exceptions are some unexpected situations that a programmer may face while programming. In this article, we will discuss an Exception in Java along with the cause of the exception, types of Java exceptions.

We will also see what is an exception hierarchy in Java.

What is Java Exception?

Exception, in general, refers to some contradiction or unexpected situation, or in short, an unexpected error that occurs during program execution. There may be some cases during program development, where the programmer is not sure that this code-fragment is going to work correctly or not.

The reason for this is that sometimes the resources are not available or sometimes the range of an array is invalid. These types of anomalous situations are called exceptions and the way to handle them is called exception handling.

The unexpected errors or bugs during the runtime or normal execution of a program is a Java Exception.

This exception causes disruption in the execution of the program.

Examples of Java Exception

Some common examples of Exceptions in Java are:

  • Divide by zero errors
  • Trying to access the array elements with an invalid index
  • Invalid input data by the user
  • Hard disk crash
  • Opening a file that does not exist
  • Heap memory exhausted
  • Network connection loss in the middle of a communication
  • JVM has run out of memory.

Causes of Exception in Java

An exception in Java occurs during the execution of a program. Exceptions are the unexpected events that occur during runtime and disrupts the normal flow of program execution.

Some causes of exceptions can be:

  • by user,
  • by programmer,
  • or by corrupted or failed physical resources.

Types of Exception in Java

We have three categories of Exceptions in Java. These are Checked Exceptions, Unchecked Exceptions, and Errors. Let’s discuss each of them in detail.

1. Checked Exceptions in java

A checked exception is a compile-time exception, that is, a Java compiler checks or notifies during the compilation-time. They occur during the compile-time.

The compiler checks the checked exceptions during compilation to check whether the programmer has written the code to handle them or not. The programmer cannot simply ignore these exceptions and should take care to handle these exceptions.

If the programmer does not write the code to handle them then there will be a compilation error. A method that throws a checked exception needs to either specify or handle it.

A checked exception extends the Exception class. Some checked Exceptions are SQLException, IOException, ClassNotFoundException, InvocationTargetException, etc.

For example, if we write a program to read data from a file using a FileReader class and if the file does not exist, then there is a FileNotFoundException.

Code to illustrate the concept of checked exception:

package com.techvidvan.exceptions;
import java.io.File;
import java.io.FileReader;
public class CheckedExceptions
{
  public static void main(String args[])
  {
    File file = new File("/home/techvidvan/file.txt");
    FileReader fileReader = new FileReader(file);
  }
}

Output:

Exception in thread “main” java.lang.Error: Unresolved compilation problem:
Unhandled exception type FileNotFoundException
at project1/com.techvidvan.exceptions.CheckedExceptions.main(CheckedExceptions.java:10)
SQLException

This type of exception occurs when a user attempts to execute invalid queries on a database and there are database access errors.

IOException

This type of exception occurs when a JVM fails to open an I/O stream file.

ClassNotFoundException

This type of exception occurs when the JVM is unable to find the required class. It may occur when a class is removed from the CLASSPATH.

2. Unchecked Exceptions in Java

An exception that occurs during the execution of a program is called an unchecked or a runtime exception. Unlike the checked exceptions, the compiler generally ignores these exceptions during compilation rather, they are checked during the runtime.

Therefore, the compiler does not check whether the programmer has written the code to handle them or not but it is the responsibility of the programmer to handle the unchecked exceptions and provide a safe exit.

For example, if a program attempts to divide a number by zero. Or, when there is an illegal arithmetic operation, this impossible event generates a runtime exception.

Suppose, we declare an array of size 10 in a program, and try to access the 12th element of the array, or with a negative index like -5, then we get an ArrayIndexOutOfBounds exception.

Some unchecked exceptions are ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, NumberFormatException, InputMismatchException, IllegalStateException, etc. We will discuss each of them with an example.

ArrayIndexOutofBound

ArrayIndexOutOfBound Exception causes when a programmer tries to access an invalid index of the array (the array index that does not exist). That is, the programmer attempts to access an array with an invalid index.

If the value of the array index is either beyond the array length or it is negative, then such error occurs.

Code to illustrate the concept of unchecked exception- ArrayIndexOutOfBounds Exception:

package com.techvidvan.exceptions;
public class UnCheckedExceptions
{
  public static void main(String args[])
  {
    //ArrayIndexOutOfBoundsException
    int array[] = {1, 2, 3, 4, 5};
    System.out.println(array[7]);

  }
}

Output:

Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: Index 7 out of bounds for length 5
at project1/com.techvidvan.exceptions.UnCheckedExceptions.main(UnCheckedExceptions.java:8)
Arithmetic Exceptions

This type of exception occurs when a user tries to attempt an incorrect arithmetic operation in the program. For example, if you divide any number by zero, then there will be an ArithmeticException. Let us consider the following code snippet:

Code to illustrate the concept of unchecked exception- ArithmeticException:

package com.techvidvan.exceptions;
public class UnCheckedExceptions
{
  public static void main(String args[])
  {
    int number1 = 10;
    int number2 = 0;
    //Arithmetic Exception
    int result = number1/number2;
    System.out.println("Result of 10/0 is: " + result);

  }
}

Output:

Exception in thread “main” java.lang.ArithmeticException: / by zero
at project1/com.techvidvan.exceptions.UnCheckedExceptions.main(UnCheckedExceptions.java:10)

Note: In case of unchecked exceptions, the compiler will never force you to declare them in the method using throws keyword or to use a try-catch block to handle them.

NullPointerException in Java

This type of exception occurs when the JVM attempts to perform an operation on an object that points to no data, or null. For example, consider the following code snippet:

Code to illustrate the concept of unchecked exception- NullPointerException:

package com.techvidvan.exceptions;
public class UnCheckedExceptions
{
  public static void main(String args[])
  {
    //NullPointerException
    String myString = null; // null value
    System.out.println(myString.charAt(0));
  }
}

Output:

Exception in thread “main” java.lang.NullPointerException
at project1/com.techvidvan.exceptions.UnCheckedExceptions.main(UnCheckedExceptions.java:8)
NumberFormatException in Java

This type of exception occurs when a program attempts to convert a string to a numeric datatype. For example, consider the following code snippet:

Code to illustrate the concept of unchecked exception- NumberFormatException

package com.techvidvan.exceptions;
public class UnCheckedExceptions
{
  public static void main(String args[])
  {
    // "Number" is not a integer, it is string
    //NumberFormatException
    int number = Integer.parseInt ("Number") ;
    System.out.println(number);
  }
}

Output:

Exception in thread “main” java.lang.NumberFormatException: For input string: “Number”
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
at java.base/java.lang.Integer.parseInt(Integer.java:658)
at java.base/java.lang.Integer.parseInt(Integer.java:776)
at project1/com.techvidvan.exceptions.UnCheckedExceptions.main(UnCheckedExceptions.java:8)
IllegalArgumentException in Java

When we pass an inappropriate or incorrect argument to a method, then this type of exception occurs. For example, if we define a method that accepts only non-empty string parameters.

But, the user provides a null string as an input. In such cases, we will get an IllegalArgumentException to indicate that you cannot pass a null input string to the method.

IllegalStateException in Java

When the state of the environment does not match the input operation, then the IllegalStateException occurs.

3. Errors in java

An Error is not an exception but we consider it as a type of exception. An error is a severe problem or situation that is impossible for a user or a developer to recover.

The cause of Errors in Java is when a user overlooks a code or rarely takes care of a mistake. For instance, if a queue is full and overflow occurs, a blunder will emerge.

Some Errors in Java are VirtualMachineError, OutOfMemoryError, AssertionError, etc.

Consider a situation, when a program attempts to allocate memory from the JVM but there is not enough space to satisfy the user request. Or, when a program tries to load a class file by calling Class.forName() method and the class file is corrupt. Such exceptions are known as an error.

Error vs Exception

Error

An Error indicates a non-recoverable condition and therefore we should not write the code to catch it. Errors usually cause the JVM to display a message and exit.

Exception

Exception is a recoverable condition that a program might try to handle.

Exception Hierarchy in Java

Below is a diagram of the exception hierarchy in Java. The Throwable class is the parent class of all Errors and Exceptions classes. The Error object describes internal errors that are non-resolvable for example resource exhaustion, etc.

An Exception object describes a recoverable error that a programmer should handle properly.

Let’s talk about this class hierarchy:

Throwable class

It is the root class of all exception classes. Its immediate subclasses are:

  • Error class
  • Exception class
Exception class

This class handles conditions that user programs can reasonably deal with. The exceptions are usually the result of some flaws in the program.

Some examples of Exceptions are:

  • Division by zero error
  • Array out-of-bounds error
Error class

Error class is an abnormal condition and a program should not try to catch or handle it on its own.

Some examples of Errors are:

  • Out of memory errors
  • Hard Disk crash

How does the JVM handle an exception- Default Exception Handler in Java

Whenever an exception occurs within a method, some activities take place internally. The following points summarize these activities:

  • When an exception occurs inside a method, the method gives the object of exception to the JVM to handle it. We call this process of creating an exception object and handing it to the runtime system as throwing an exception. The created object contains information about the error, including its type and the state of the program during the occurrence of the error.
  • Then, the JVM searches the method call stack that contains the method that contains a code to handle the exception.
  • When the system finds an appropriate handler, it passes the exception to the handler.
  • If the runtime system finds no appropriate exception handler, then both the runtime system and the program terminates and uses the default exception handler.

Java Exception Methods

Following is the list of important methods available in the Throwable class.

S.N. Method  Description
1 public String getMessage() This method returns a detailed description of the occurred exception.
2 public Throwable getCause() This method returns the cause of the occurred exception 
3 public String toString() This method returns the result of the getMessage() method concatenated with the name of the class.
4 public void printStackTrace() This method prints the result of the toString() method along with the stack trace to the error output stream.
5 public StackTraceElement [] getStackTrace() This method returns an array containing each element of the stack trace. 

User-defined or customized Exception in Java

We know that Java comes with a rich set of in-built exception classes, but, there are some situations in which we may encounter various application-specific errors. We need to define our own exceptions to handle such errors or exceptions.

Therefore, we can create customized exceptions to serve this purpose.

Rules for Java Exception

While defining a user-defined exception, we need to take care of the following aspects:

  • The user-defined exception class should extend the Exception class.
  • In the user-defined exception class, the programmer should override the toString() method.

Code to create and use a user-defined exception:

package com.techvidvan.exceptions;
public class NegativeAgeException extends Exception
{
  private static int age;
  public NegativeAgeException(int age)
  {
    this.age=age;
  }
  public String toString()
  {
    return "Age can't be negative";
  }
  public static void main(String args[]) throws Exception
  {
    NegativeAgeException obj = new NegativeAgeException( -10 );
    if(age < 0)
    {
      throw new NegativeAgeException(age);
    }
    else
    {
      System.out.println("Entered age is: " +age);
    }
  }
}

Output:

Exception in thread “main” Age can’t be negative
at project1/com.techvidvan.exceptions.NegativeAgeException.main(NegativeAgeException.java:20)

Summary

There are three types of exceptions in Java that we studied today in this article. They are checked, unchecked, and error. We can handle every exception in our own way. We also covered some important subtypes of checked and unchecked exceptions with examples.

Coming to the end of this article, you would have become an expert in creating your own custom exceptions.

Thank you for reading this article. Do share it on Social Media.

Keep Learning 🙂