Java Exceptions

Java Exception handling refers to three keywordstry, catch and throw. While programming in Java, there often comes scenarios when command prompt shows error. Errors occur when there is some problem in the code and it cannot be compiled. There can be different reasons for errors, such as:

  • Syntax error
  • JVM ran out of memory
  • File cannot be opened
  • Wrong input error
  • Error made by programmer in coding
  • Undefined response
  • Network Connection is unavailable or gets interrupted

What is Java Exception

An exception is an issue that occurs during the execution of a program for example, anything divided by zero arises an exception. The response to such undefined conditions when program is running is a Java exception. When program encounters an exception it stops running and generates an error message. In technical terms it is referred to as Java will throw an exception or Java will throw an error.

The example below shows a code that will generate error.

public class Example {
   
   public static void main(String args[]) {
      int arr[] = {1, 2, 3, 4};
      System.out.println(arr[5]);
   }
}

Since the array index ends at 4 so, the JVM will generate an array index out of bound error on command line. The error will be something like:

All the built in exceptions exist in the java.lang.Exception class. The class name is Throwable. Other than exceptions, the Throwable class also contains a subclass called Error. This subclass is responsible for showing errors. There are two main subclasses in Exception class:

  • IOException class
  • RuntimeException class

Exception Methods

The below table shows a list of exception methods and their descriptions provided by the Throwable class:

Sr.No.MethodsDescription
1.public String getMessage()This method returns an error message with its details. It tells about the exception that is occurred.
2.public void printStackTrace()This method prints the output of toString() method. It also prints the stack trace to System.err that is the error output stream.
3.public Throwable getCause()This method returns the cause of exception as a reference of Throwable object.
4.public StackTraceElement [] getStackTrace()This method returns all elements present in the stack element in the form of array. The element of array at 0 index represents the beginning of stack. While the element at the last index of array represents the method at the end of stack.
5.public String toString()This method concatenates the name of class with the output of get message and returns it as a string.
6.public Throwable fillInStackTrace()This method fills the stack trace of specified Throwable object. It keeps the current stack trace and adds the new information with previous information.
Java Exception Methods

Java Exception Handling

The three keywords that perform Java exceptional handling are:

try: A try is a block of code that checks for errors in the code while its execution. It is followed by catch block.

catch: When an exception occurs, the piece of code in the block catch is executed. The try and catch blocks work in pair. Programmer can implement more than one catch blocks.

throw: As clear from the keyword itself, the throw block throws an exception when it finds an error. Programmer can also define his/her own custom error messages using throw.

The try catch Block

The syntax of using try, catch and throw blocks is:

Here is an example that handles exception in a java code using try and catch blocks:

public class Example {
  public static void main(String[] args) {
    try {
      int[] arr = {1, 2, 3, 4, 5};
      System.out.println(arr[6]);
    } catch (Exception e) {
      System.out.println("An error occurred while execution.");
    }
  }
}

Here instead of built in exception message, user defined message is displayed. The exception message is defined in the catch block. The output of the above code after compilation is:

The finally Block

The finally block uses finally keyword and is written after try and catch blocks. The code body in finally block is always executed regardless of the result of try catch blocks. The syntax of writing finally block is:

Here is an example that shows a code using the finally block after try catch blocks.

public class Main {
  public static void main(String[] args) {
    try {
      int[] arr = {1, 2, 3, 4, 5};
      System.out.println(arr[6]);
    } catch (Exception e) {
      System.out.println("An error occurred while execution.");
    } finally {
      System.out.println("The 'try catch' block is exited and the finally block is always executed.");
    }
  }
}

The output of the above code after compilation is:

The throw Block

The throw statement uses throw keyword. It is used to throw user defined errors when the method does not handle exceptions. The throw statement uses new keyword along with a Java exception type. The exception types defined by Java are:

  • ArrayIndexOutOfBoundsException
  • SecurityException
  • FileNotFoundException
  • ClassNotFoundException
  • NoSuchFieldException 
  • ArithmeticException, etc.

All these are Java exceptions. The below example shows the use of throw statement with java exception in the code.

public class Example {
  static void checkDiscount(int price) { 
    if (price < 500) {
      throw new ArithmeticException("Sorry! This item does not fall in the discount category."); 
    } else {
      System.out.println("Congratulations! There is 20 % percent discount on this item."); 
    }
 } 
 
 public static void main(String[] args) { 
   checkDiscount(50); 
 } 
}

The output of the above code after compilation is:

In the same code above if we change the price to 1500:

public class Example {
  static void checkDiscount(int price) { 
    if (price < 500) {
      throw new ArithmeticException("Sorry! This item does not fall in the discount category."); 
    } else {
      System.out.println("Congratulations! There is 20 % percent discount on this item."); 
    }
 } 
 
 public static void main(String[] args) { 
   checkDiscount(1500); 
 } 
}

In this case, the output of the above code after compilation will be: