Types of Exceptions in Java

built-in exception
user-defined exception

In the previous blog, we learned about what is an exception handling. If you want to learn about it visit Exception Handling in Java . In this blog, we will go through the types of Exceptions.

...

There are two types of Exceptions

  1. Built-in Exception
  2. User-defined Exception

  1. Built-in Exceptions
  2. Built-in Exceptions are the exceptions that are already available in the Java libraries. Following are the built-in exceptions:

    1. ArrayIndexOutOfBoundsException
    2. The exception ArrayIndexOutOfBoundsException is thrown when we attempt to access the array with an invalid index. For example, the size of an array is 4 and we are trying to access the 5th element which is not present in the array as the size is 4. In this case, the compiler throws an exception i.e.ArrayIndexOutOfBoundsException

      e.g.

      class ArrayIndexOutOfBoundEx{
        public static void main(String args[]){
          try{
            int a[] = new int[4];
            a[5] = 90;
          }
          catch(ArrayIndexOutOfBoundsException ex){
            System.out.println ("Array Index Out Of Bounds Exception");
          }
        }
      }

      Output

      Array Index Out Of Bounds Exception
    3. ArithmeticException
    4. ArithmeticException is an exception that is thrown when an exceptional arithmetic condition occurs. For example when we try to divide a number by 0 then in this case the compiler gives an exception.

      e.g.

      class ArithmeticExceptionEx{
        public void displayResult(int no1, int no2){
          try{
            int result = no1/no2;
            System.out.println("The result is:"+ result);
          }catch(ArithmeticException ex){
            System.out.println("Divide by Zero Exception");
          }
        }
        public static void main(String args[]){
          ArithmeticExceptionEx exObj = new ArithmeticExceptionEx();
          exObj.displayResult(60,0);
        }
      }

      Output

      Divide by Zero Exception
    5. ClassNotFoundException
    6. ClassNotFoundException is the exception that is thrown when we try to access the class whose definition is not found. For example, we are trying to access the Class named Atrowel which is not present, so in this case, the compiler will throw an exception,i.e. ClassNotFoundException.

      e.g.

      public class ClassNotFoundExceptionEx {
        public static void main(String args[]){
          try {
              Class.forName("Atrowel");
          }
          catch (ClassNotFoundException ex) {
            System.out.println("Class not Found");
          }
        }
      }

      Output

      Class not Found
    7. FileNotFoundException
    8. FileNotFoundException is an exception that is thrown when a try is not accessible or does not open. For example, we try to access a file named Example.txt and that file doesn’t exist then the compiler throws FileNotFoundException.

      e.g.

      import java.io.File;
      import java.io.FileNotFoundException;
      import java.io.FileReader;
      class FileNotFoundEx {
        public static void main(String args[]){
          try{
            File fileObj = new File("C://Example.txt");
            FileReader fileReaderObj = new FileReader(fileObj);
          } catch (FileNotFoundException ex) {
            System.out.println("File does not exist");
          }
        }
      }

      Output

      File does not exist
    9. IOException
    10. IOException is the exception that is thrown when there is a failure in input/output operation or if there is an interrupt due to some reason, then the compiler throws an exception called IOException. For example, if we have given a print command to a Printer and Printer has started printing pages and in between Printer goes out of Page, then the compiler throws an exception called IOException.

      e.g.

      import java.util.Scanner;
      class IOException_Demo {
        public static void main(String[] args){
          Scanner scanObj = new Scanner("Welcome to Javashort Kicks");
          System.out.println("" + scanObj.nextLine());
          System.out.println("IOException: "+ scanObj.ioException());
          scanObj.close();
        }
      }

      Output

      Welcome to Javashort Kicks
      IOException: null
    11. NoSuchMethodException
    12. NoSuchMethodException is an exception that is thrown when we try to access the method which is not found. For example, suppose we try to access a method called displayResult and that method is not present in the class, then in this case the compiler will throw an exception i.e. NoSuchMethodException.

      e.g.

      public class NoSuchMethodEx {
        public void displayString(String str){
          System.out.println(str);
        }
        public static void main(String[] args){
          NoSuchMethodEx exObj = new NoSuchMethodEx();
          exObj.display("Welcome to Java Short Kicks");
        }
      }

      Output

      error: cannot find symbol
      exObj.display("Welcome to Java Short Kicks");
                  ^
      symbol:   method display(String)
        location: variable exObj of type NoSuchMethodEx
      1 error
    13. NullPointerException
    14. The NullPointerException exception is thrown when the program attempts to use an object reference that has a null value. For example, if we try to use the exObj reference which has the null value then the compiler throws an exception called NullPointerException.

      e.g.

      public class NullPointerEx{
        public static void main(String args[]){
          try {
            String msg = null;
            System.out.println(msg.indexOf(2));
          }catch(NullPointerException ex) {
            System.out.println("Null Pointer Exception");
          }
        }
      }

      Output

      Null Pointer Exception
    15. NumberFormatException
    16. NumberFormatException is an exception that is thrown when a program tries to convert a string with improper format into numeric values.

      e.g.

      public class  NumberFormatEx{
        public static void main(String args[]){
          try {
            int value1 = Integer.parseInt ("10");
            int value2 = Integer.parseInt ("Atrowel");
            System.out.println(value1);
            System.out.println(value2);
          }catch(NumberFormatException e){
            System.out.println("Number format exception");
          }
        }
      }

      Output

      Number format exception
    17. StringIndexOutOfBoundsException
    18. StringIndexOutOfBoundsException is thrown when the index of a string is either negative or greater than the length of the string. For example, suppose the length of an string is 20 and we are trying to access the 22th element then in this case the compiler will throw an exception i.e. StringIndexOutOfBoundsException.

      e.g.

      public class StringIndexOutOfBoundEx{
        public static void main(String args[]){
          try {
            String strValue = "Welcome to JavaShortKicks";
            char element = strValue.charAt(26);
            System.out.println(element);
          }
          catch(StringIndexOutOfBoundsException ex) {
            System.out.println("StringIndexOutOfBoundsException");
          }
        }
      }

      Output

      StringIndexOutOfBoundsException
    19. IllegalArgumentException
    20. IllegalArgumentException is an exception that is thrown when a method receives an argument that is improper or not accurate for the given condition, then the IllegalArgumentException is thrown. For example, if suppose there are two numbers and division needs to perform, and if one number from these two is zero then it will throw the exception i.e. IllegalArgumentException.

      e.g.

      import java.io.*;
      public class IllegalArugementEx {
        public void calculate(int no1, int no2){
          if(no2 <=0){
            System.out.println("Number cannot be less than or equal to 0");
          }
          else{
            int result = no1/no2;
            System.out.println("The result is:"+ result);
          }
        }
        public static void main(String[] args) {
          IllegalArugementEx exObj = new IllegalArugementEx();
          exObj.calculate(90,0);
        }
      }

      Output

      Number cannot be less than or equal to 0
    21. IllegalStateException
    22. IllegalStateException is an exception that is thrown when a method is not accessible for the specific operation which we are performing.

      e.g.

      import java.util.*;
      public class IllegalStateEx{
        public static void main(String args[]) {
          List<String> list = new ArrayList<String>();
          list.add("Java");
          list.add("C");
          list.add("C#");
          list.add("C++");
          Iterator<String> iterObj = list.iterator();
          while (iterObj.hasNext()) {
            iterObj.remove();
          }
        }
      }

      Output

      Exception in thread "main" java.lang.IllegalStateException
      at java.base/java.util.ArrayList$Itr.remove(ArrayList.java:1010)at IllegalStateEx.main(IllegalStateEx.java:12)

      In this example we are calling remove() before the next() method of iterable will throw an exception called IllegalStateException.


  3. User-defined Exceptions
  4. In Java we can define our own exceptions and throw them with the help of throw keyword. These exceptions are known as custom exceptions or user-defined exceptions. In order to create our own exception we should create an Exception class which will be the subclass for the Exception class. Note we should always extend the Exception class whenever we create our Exception class. For example:

    e.g.

    class CustomExceptionEx extends Exception

    Once we have defined our exception, we can also create a default constructor which is as follows:

    e.g.

    CustomExceptionEx(){
    }

    We can even create a parameterized constructor by passing a string as parameters so that we can use this string parameter to store the details of exceptions. Once this is done we can call the superclass constructor and pass the string in that.

    e.g.

    CustomExceptionEx(String strValue){
      super(strValue);
    }

    In order to call this Exception we should create an object of it and throw it using the throw keyword.

    e.g.

    CustomExceptionEx custEx = new MyException("Exception details");
    throw custEx;

    We will go through the program which illustrates the User-defined Exception

    e.g.

    class CustomExceptionEx extends Exception {
      public CustomExceptionEx(String str){
        super(str);
      }
    }
    public class TestCustomException {
      public static void main(String args[]){
        try {
          throw new CustomExceptionEx("Custom Exception");
        }
        catch (CustomExceptionEx ex) {
          System.out.println("Caught the");
          System.out.println(ex.getMessage());
        }
      }
    }

    Output

    Caught the
    Custom Exception
Get in Touch

Atrowel will be pleased to receive your feedback and suggestions. Those of you who would like to contribute, please send us an email.