Java – Multiple Choice Questions and Answers – Exception Handling

HOME



public class QAAutomation {
    
     public static void main(String[] args) {
        try {
            System.out.println("Inside try");
            throw new RuntimeException("Error");
        } finally {
            System.out.println("Inside finally");
        }
    }
}

 public class QAAutomation {
    
    static void method() throws Exception {
        throw new Exception("Error occurred");
    }

    public static void main(String[] args) {
        method();
    }
}


 class CustomException extends Exception {
    public CustomException(String message) {
        super(message);
    }
}

public class Test {
    public static void main(String[] args) {
        try {
            throw new CustomException("Custom error occurred");
        } catch (CustomException e) {
            System.out.println(e.getMessage());
        }
    }
}

public class Test {
    
    public static void main(String args[]) {
        try {
            int a, b;
            b = 0;
            a = 5 / b;
            System.out.print("A");
        } catch (ArithmeticException e) {
            System.out.print("B");
        } finally {
            System.out.print("C");
        }
    }
}

public class Test {
    public static void main(String args[])
    {
        try
        {
            int i, sum;
            sum = 10;
            for (i = -1; i < 3 ;++i)
                sum = (sum / i);
        }
        catch(ArithmeticException e)
        {
            System.out.print("0");
        }
        System.out.print(sum);
    }
}



public class Test{
    public static void main(String[] args) {
        try {
            System.exit(0);
        } finally {
            System.out.println("Finally executed");
        }
    }
}



  public class Test {
         public static void main(String[] args) {
             String str = null;
             try {
                 System.out.println(str.length());
             } catch (NullPointerException e) {
                 System.out.println("Caught a NullPointerException");
             }
         }
     }

import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class Test {
    public static void readFile() throws IOException {
        File file = new File("example.txt");
        FileReader reader = new FileReader(file);
        reader.close();
    }

    public static void main(String[] args) {
        try {
            readFile();
        } catch (IOException e) {
            System.out.println("IOException handled");
        }
    }
}


public class Test {
    
    public static void main(String[] args) {

        try {
            int[] numbers = {1, 2, 3};
            System.out.println(numbers[3]);
            int division = 10 / 0;
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Array index is out of bounds");
        } catch (ArithmeticException e) {
            System.out.println("Cannot divide by zero");
        } finally {
            System.out.println("Finally block executed");
        }
        System.out.println("Rest of the program");
    }
}

public class Test {
    public static void main(String args[])
    {
        try
        {
            System.out.print("Hello" + " " + 1 / 0);
        }
        catch(ArithmeticException e)
        {
            System.out.print("World");
        }
    }
}




public class Test {

    public static void main(String[] args) {
        try {
            throw new Exception("First Exception");
        } catch (Exception e) {
            try {
                throw new Exception("Second Exception");
            } catch (Exception ex) {
                System.out.println(ex.getMessage());
            }
        }
    }
}

public class Test {
    public static void main(String[] args) {
        try {
            throw new Error("Fatal error");
        } catch (Exception e) {
            System.out.println("Exception");
        } catch (Error e) {
            System.out.println("Error");
        }
    }
}

public class Test {
    public static void main(String[] args) {
        try {
            int[] array = new int[5];
            System.out.println(array[5]);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("ArrayIndexOutOfBoundsException");
        } finally {
            System.out.println("Finally block executed.");
        }
    }
}

public class Test {
    public static void main(String[] args) {
        try {
            throw new NullPointerException();
        } catch (RuntimeException e) {
            System.out.println("RuntimeException");
        } catch (Exception e) {
            System.out.println("Exception");
        }
    }
}


Java Tutorials

Java is a general-purpose programming language that is a concurrent, class-based, and object-oriented language. Java follows the concept of “write once and run anywhere (WORA).” This means that compiled Java code can be run on all different platforms that support Java. There’s no need for recompilation.

Eclipse IDE

Chapter 1 How to Download and Install Eclipse IDE
Chapter 2 How to Clone a project from GitLab using Eclipse
Chapter 3 How to Export Eclipse projects to GitLab

IntelliJ IDE

Chapter 1 How to install IntelliJ on Windows
Chapter 2 How to create a Java project in IntelliJ
Chapter 3 How to Clone a project from GitLab using IntelliJ
Chapter 4 How to Export IntelliJ project to GitLab

Basics of Java

Chapter 1 How to Download & Install Java JDK 11 in Windows
Chapter 2 Data Types and Operators in Java
Chapter 3 Decision Making in Java – If, If Else, Switch, Break, Continue
Chapter 4 Loop Control Statements in Java – For, While, Do While, Enhanched For Loop
Chapter 5 String Manipulation
Chapter 6 Difference between == and equals() method in Java
Chapter 7 Arrays in Java
Chapter 8 Java Access Modifiers: Explained with Examples
Chapter 9 ArrayList in Java
Chapter 10 How to compare ArrayLists – contains?
Chapter 11 How to compare ArrayLists – containsAll method?
Chapter 12 Methods in Java
Chapter 13 Method Overloading in Java
Chapter 14 Constructors in Java   
Chapter 15 This Keyword in Java   
Chapter 16 Static Keyword – Static Variable and Static Method in Java
Chapter 17 Difference between Static Method and Non-Static Method
Chapter 18 How to use Java Lambda expression to create thread via Runnable function
Chapter 19 runAsync and supplyAsync in ComputableFuture in Java8
Chapter 20 HashMap in Java
Chapter 21 LinkedHashMap in Java
Chapter 22 Iterators in Java

OOPs Concepts

Chapter 1 Class and Object in Java
Chapter 2 Inheritance in Java
Chapter 3 Encapsulation in Java
Chapter 4 Polymorphism in Java
Chapter 5 Abstraction in Java
Chapter 6 Interface in Java
Chapter 7 Difference between Abstract Class and Interface

Exceptions in Java

Chapter 1 Exception Handling in Java
Chapter 2 Java Exceptions Tutorial: Built-in and User-defined Exceptions
Chapter 3 Flow control in try catch finally in Java
Chapter 4 Multiple Catch Exceptions
Chapter 5 Throw in Java
Chapter 6 Throws in Java

Data Handling (Excel Manipulation)

Chapter 1 How to download and install Apache POI
Chapter 2 Reading Excel Data with Apache POI in Java
Chapter 3 How to Write Data to Excel File in Java using Apache POI
Chapter 4 How to update existing excel in Java
Chapter 5 Java Excel Tutorial: Creating Excel with Formulas Using Apache POI
Chapter 6 Change Font Style in Excel with Apache POI – NEW

Multiple Choice Questions

Chapter 1 Multiple questions on Exception Handling in Java

Java Library

Chapter 1 AssertJ – Fluent Assertions in Java

Multiple questions on Exception Handling in Java

HOME

In this tutorial, you will see the various questions related to Exception Handling.

Example1

public class ExceptionHandlingDemo {

	public static void main(String[] args) {

		try {
			int a[] = new int[5];
			a[5] = 30 / 0;
		} catch (ArithmeticException e) {
			System.out.println("Arithmetic Exception occurs");
		} catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("ArrayIndexOutOfBounds Exception occurs");
		} catch (Exception e) {
			System.out.println("Parent Exception occurs");
		}
		System.out.println("Continue the program..");
	}
}

Here, we have multiple catch blocks with different types of exceptions. 30 is divided by 0 which throws ArithmeticException. So, the catch block for ArithmeticException is executed. Once the try-catch block is executed, the program runs in normal flow.


Example2

public class ExceptionHandlingDemo {

	public static void main(String[] args) {

		try {
			int a[] = new int[5];
			a[5] = 30 / 15;
		} catch (ArithmeticException e) {
			System.out.println("Arithmetic Exception occurs");
		} catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("ArrayIndexOutOfBounds Exception occurs");
		} catch (Exception e) {
			System.out.println("Parent Exception occurs");
		}
		System.out.println("Continue the program..");
	}
}

Here, we are trying to access a[5] where index 5 is out of range, which throws ArrayIndexOutOfBoundsException. So, the catch block for ArrayIndexOutOfBoundsException is executed. Once the try-catch block is executed, the program runs in normal flow.


Example3

public class ExceptionHandlingDemo {

	public static void main(String[] args) {
		try {
			int a[] = new int[5];

			System.out.println(a[7]);
		} catch (ArithmeticException e) {
			System.out.println("Arithmetic Exception occurs");
		} catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("ArrayIndexOutOfBounds Exception occurs");
		} catch (Exception e) {
			System.out.println("Parent Exception occurs");
		}
		System.out.println("Continue the program..");
	}
}

Output
ArrayIndexOutOfBounds Exception occurs
Continue the program..

Here, we are trying to access a[7] where index 7 is out of range, which throws ArrayIndexOutOfBoundsException. So, the catch block for ArrayIndexOutOfBoundsException is executed. Once the try-catch block is executed, the program runs in normal flow.


Example4

public class ExceptionHandlingDemo {

	public static void main(String[] args) {
		try {
			int a[] = new int[5];
			a[5] = 30 / 0;
			System.out.println(a[10]);
		} catch (ArithmeticException e) {
			System.out.println("Arithmetic Exception occurs");
		} catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("ArrayIndexOutOfBounds Exception occurs");
		} catch (Exception e) {
			System.out.println("Parent Exception occurs");
		}
		System.out.println("Continue the program..");
	}
}

Here, the try block contains two exceptions. But at a time only one exception occurs and its corresponding catch block is executed. So, the first exception is 30 divided by 0 which throws an ArithmeticException. So, the catch block for ArithmeticException is executed. Once the corresponding catch block is executed, the program runs in normal flow.


Example5

public class ExceptionHandlingDemo {

    public static void main(String[] args) {
        try {
            String name = null;
            System.out.println(name.length());
        } catch (ArithmeticException e) {
            System.out.println("Arithmetic Exception occurs");
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("ArrayIndexOutOfBounds Exception occurs");
        } catch (Exception e) {
            System.out.println("Parent Exception occurs");
        }
        System.out.println("Continue the program..");
    }
}

Here, the try block contains NullPointerException. But, there is no NullPointerException present in any of the catch blocks. In such a case, the catch block containing the parent exception class Exception will be invoked.


Example6

public class ExceptionHandlingDemo {

	public static void main(String[] args) {
		try {
			int a[] = new int[5];
			a[5] = 30 / 0;
		} catch (Exception e) {
			System.out.println("common task completed");
		} catch (ArithmeticException e) {
			System.out.println("Arithmetic Exception occurs");
		} catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("ArrayIndexOutOfBounds Exception occurs");
		}
		System.out.println("Continue the program..");
	}
}

Here, the order of exceptions is not maintained like most specific to general exceptions. The exception is the parent exception, so should be mentioned as the last exception. As a result, there is a compile-time error.


Example7

public class ExceptionHandlingDemo {

    public static void main(String args[]) {
        int x = 0;
        int y = 10;
        int z = y/x;
    }
}

Here, ArithmeticException is an unchecked exception that is not checked at a compiled time. So the program compiles fine but throws ArithmeticException.


Example8

public class ExceptionHandlingDemo {

    public static void main(String[] args) {
        try {
            int a[] = { 1, 2, 3, 4 };
            for (int i = 1; i <= 4; i++) {
                System.out.println("a[" + i + "]=" + a[i]);
            }
        }

        catch (Exception e) {
            System.out.println("error = " + e);
        }

        catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("ArrayIndexOutOfBounds Exception occured");
        }
    }
}

Here, ArrayIndexOutOfBoundsException has been already caught by the base class Exception. When a subclass exception is mentioned after the base class exception, then an error occurs.


Example9

public class Example9 {

	public static void main(String[] args) {
		try {
			int a[] = { 1, 2, 3, 4 };
			for (int i = 1; i <= 4; i++) {
				System.out.println("a[" + i + "]=" + a[i]);
			}
		}

		catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("ArrayIndexOutOfBounds Exception occured");
		}

		catch (Exception e) {
			System.out.println("error = " + e);
		}
	}
}

Here, the try block prints a[1] to a[3] and then throws ArrayIndexOutOfBoundsException which is handled by the corresponding catch block.


Example10

public class ExceptionHandlingDemo {

	public static void main(String[] args) {

		// outer try block
		try {

			// inner try and catch block 1
			try {
				System.out.println("going to divide by 0");
				int b = 40 / 0;
			}
			catch (ArithmeticException e) {
				System.out.println(e);
			}

			// inner try and catch block 2
			try {
				int a[] = new int[5];

				// assigning the value out of array bounds
				a[5] = 4;
			}
			catch (ArrayIndexOutOfBoundsException e) {
				System.out.println(e);
			}

			System.out.println("No more inner try catch block");
		}

		// catch block of outer try block
		catch (Exception e) {
			System.out.println("Handled the exception of outer try");
		}

		System.out.println("Continue the program..");
	}
}

Here, the first inner try-catch block is executed. Then second inner try-catch block is executed and at last outer try-catch block is executed. Post all these, the program runs in normal flow.


Example11

public class ExceptionHandlingDemo {

	public static void main(String[] args) {

        // outer try block
        try {

            // inner try block 1
            try {

                // inner try block 2
                try {
                    int x = 25 / 0;
                    System.out.println("Value of x :" + x);
                }

                // to handles ArrayIndexOutOfBoundsException
                catch (ArrayIndexOutOfBoundsException e) {
                    System.out.println("Arithmetic exception");
                    System.out.println(" inner try block 2");
                }
            }

            // to handle ArrayIndexOutOfBoundsException
            catch (ArrayIndexOutOfBoundsException e) {
                System.out.println("Arithmetic exception");
                System.out.println("inner try block 1");
            }
        }

        // to handle ArithmeticException
        catch (ArithmeticException e) {
            System.out.println(e);
            System.out.println("Outer try block");
        } catch (Exception e) {
            System.out.print("Exception");
            System.out.println("Handled in main try block");
        }
    }
}

Here, the try block within the nested try block (inner try block 2) does not handle the exception. The control is then transferred to its parent try block (inner try block 1) and it also does not handle the exception, then the control is transferred to the main try block (outer try block) where the appropriate catch block handles the exception. 


Example12

public class ExceptionHandlingDemo {

	public static void main(String[] args) {

		// outer try block
		try {

			// inner try block 1
			try {

				// inner try block 2
				try {
					int x = 25 / 0;
					System.out.println(x);
				}

				// to handles ArrayIndexOutOfBoundsException
				catch (ArrayIndexOutOfBoundsException e) {
					System.out.println("Arithmetic exception");
					System.out.println(" inner try block 2");
				}
			}

			// to handle ArithmeticException 
			catch (ArithmeticException e) {
				System.out.println("Arithmetic exception");
				System.out.println("inner try block 1");
			}
		}

		// to handle ArithmeticException
		catch (ArithmeticException e) {
			System.out.print(e);
			System.out.println("Outer try block");

		} catch (Exception e) {
			System.out.print("Exception");
			System.out.println("Handled in main try block");
		}
	}
}

Here, the try block within the nested try block (inner try block 2) does not handle the exception. The control is then transferred to its parent try block (inner try block 1) and it does handle the exception, so the catch block of inner try block 1 handles the exception.


Example13

public class ExceptionHandlingDemo {

	public static void main(String[] args) {
		try {
			// below code do not throw any exception
			int data = 25 / 5;
			System.out.println(data);
		}

		// catch won't be executed
		catch (NullPointerException e) {
			System.out.println(e);
		}

		// This is executed whether exception occurs or not
		finally {
			System.out.println("finally block is always executed");
		}

		System.out.println("Continue the Program ..");
	}
}

Output
5
finally block is always executed
Continue the Program ..

Here, no exception is thrown, so the catch block is not executed. finally block is always executed irrespective the catch block is executed or not.


Example14

public class ExceptionHandlingDemo {

	public static void main(String[] args) {
		try {

			System.out.println("Inside the try block");

			// below code throws divide by zero exception
			int data = 25 / 0;
			System.out.println(data);
		}

		catch (NullPointerException e) {
			System.out.println("Exception handled");
			System.out.println(e);
		}

		// executes regardless of exception occurred or not
		finally {
			System.out.println("finally block is always executed");
		}

		System.out.println("Continue the Program ..");
	}
}

Here, the code throws an exception, however, the catch block cannot handle it. Despite this, the finally block is executed after the try block and then the program terminates abnormally.


Example15

public class ExceptionHandlingDemo {

	public static void main(String[] args) {
		
       try {

			System.out.println("Inside try block");

			// below code throws divide by zero exception
			int data = 25 / 0;
			System.out.println(data);
		}

		// handles the Arithmetic Exception 
		catch (ArithmeticException e) {
			System.out.println("Exception is handled");
			System.out.println(e);
		}

		// executes regardless of exception occured or not
		finally {
			System.out.println("finally block is always executed");
		}

		System.out.println("Continue the Program ..");
	}
}

Here, the code throws an exception and the catch block handles the exception. Later the finally block is executed after the try-catch block. Further, the rest of the code is also executed normally.


Example16

public class ExceptionHandlingDemo {

	public static void main(String[] args) {
		try {
			int a = 0;
			System.out.println("a = " + a);
			int b = 20 / a;
			System.out.println("b = " + b);
		}

		catch (ArithmeticException e) {
			System.out.println("Divide by zero error");
		}

		finally {
			System.out.println("inside the finally block");
		}
	}
}

Here, a is printed. Then, 20 is divided by 0, which throws ArithmeticException and control goes inside the catch block. Also, the finally block is always executed whether an exception occurs or not.


Example 17

public class ExceptionHandlingDemo {

	public static void main(String[] args) {
		int data = 50 / 0; // may throw exception

		System.out.println("rest of the code");
	}

}

Here, there is no try-catch block. So, the error is thrown.


Example 18

public class ExceptionHandlingDemo  {

	public static void main(String[] args) {
		try {
			int data1 = 50 / 0; 

		}
		catch (Exception e) {
			// generating the exception in catch block
			String name = null;
			System.out.println(name.length());
			
		}
		System.out.println("Continue the Program ..");
	}

}

Output
Exception in thread "main" java.lang.NullPointerException

Here, the catch block didn’t contain the exception code. So, enclose the exception code within a try block and use a catch block only to handle the exceptions.


Example 19

public class ExceptionHandlingDemo {

	static void checkEligibilty(int age, int marks) {
		if (age < 18 && marks < 90) {
			throw new ArithmeticException("Student is not eligible for admission");
		} else {
			System.out.println("Student Entry is Valid!!");
		}
	}

	public static void main(String[] args) {
		System.out.println("Welcome to the Admission process!!");
		checkEligibilty(17, 80);
		System.out.println("Continue the Program ..");
	}
}

Here, an unchecked exception was thrown and it is not handled, so the program halts.


Example 20

public class ExceptionHandlingDemo {

	public static void myMethod(int testnum) throws Exception {
		System.out.println("start - myMethod");
		if (testnum < 100)
			throw new Exception();
		System.out.println("end - myMethod");
		return;
	}

	public static void main(String args[]) {
		int testnum = 90;
		try {
			System.out.println("try - first statement");
			myMethod(testnum);
			System.out.println("try - last statement");
		} catch (Exception ex) {
			System.out.println("An Exception");
		} finally {
			System.out.println("finally");
		}
		System.out.println("Out of try/catch/finally - statement");
	}
}

Here, an exception is thrown in the try block, which is handled by the catch block. A finally block is executed, and then the program continues as usual.


Example 21

public class ExceptionHandlingDemo {

   public static void main(String args[]) {
      try {
         throw 10;
      }
      catch(int e) {
         System.out.println("Got the  Exception " + e);
      }
  }
}

In Java, only throwable objects (Throwable objects are instances of any subclass of the Throwable class) can be thrown as exceptions. So basic data types can not be thrown at all.


Example 22

public class ExceptionHandlingDemo {

	public static void main(String[] args) {
		
      try {
			throw new Test();
		} catch (Test t) {
			System.out.println("Got the Test Exception");
		} finally {
			System.out.println("Inside finally block ");
		}
	}
}

The output of the above program is


Example 23

class Base extends Exception {
}

class Derived extends Base {
}

 class ExceptionHandlingDemo  {

    public static void main(String[] args) {
        try {

            throw new Derived();
        } catch (Base b) {
            System.out.println("Caught base class exception");
        } catch (Derived d) {
            System.out.println("Caught derived class exception");
        }
    }
}


Example 24

public class ExceptionHandlingDemo {

	String str = "a";

    void A() {
        try {
            str += "b";
            B();
        } catch (Exception e) {
            str += "c";
        }
    }

    void B() throws Exception {
        try {
            str += "d";
            C();
        } catch (Exception e) {
            throw new Exception();
        } finally {
            str += "e";
        }

        str += "f";

    }

    void C() throws Exception {
        throw new Exception();
    }

    void display() {
        System.out.println(str);
    }

    public static void main(String[] args) {
        ExceptionHandlingDemo object = new ExceptionHandlingDemo();
        object.A();
        object.display();
    }

}

}

‘throw’ keyword is used to explicitly throw an exception.
Call to method C() throws an exception. Thus, control goes to the catch block of method B() which again throws an exception. Then finally block is always executed even when an exception occurs. Now, control goes to the catch block of method A().


Example 25

public class ExceptionHandlingDemo {

	 void m() {
        int data = 50 / 0;
    }

    void n() {
        m();
    }

    void p() {
        try {
            n();
        } catch (Exception e) {
            System.out.println("Exception Handled");
        }
    }

    public static void main(String args[]) {
        ExceptionHandlingDemo obj = new ExceptionHandlingDemo();
        obj.p();
        System.out.println("Continue the program..");
    }
}

Here, the exception occurs in the m() method where it is not handled, so it is propagated to the previous n() method where it is not handled, again it is propagated to the p() method where the exception is handled.


Example 26

public class ExceptionHandlingDemo {

	void m() {
        throw new IOException("device error");// checked exception
    }

    void n() {
        m();
    }

    void p() {
        try {
            n();
        } catch (Exception e) {
            System.out.println("Exception Handled");
        }
    }

    public static void main(String args[]) {
        ExceptionHandlingDemo obj = new ExceptionHandlingDemo();
        obj.p();
        System.out.println("Continue the program..");
    }
}

Here, the exception occurs in the m() method where it is not handled, so it is propagated to the previous n() method where it is not handled, it is propagated to the p() method where the exception is supposed to be handled, but as it is checked Exception which can not be handled by Exception.


Example 27

public class ExceptionHandlingDemo {

    void m() {
        throw new ArithmeticException("Arithmetic Exception occured ");
    }

    void n() {
        m();
    }

    void p() {
        try {
            n();
        } catch (Exception e) {
            System.out.println("Exception handled");
        }
    }

    public static void main(String args[]) {
        ExceptionHandlingDemo obj = new ExceptionHandlingDemo();
        obj.p();
        System.out.println("Continue the program..");
    }
}

Here, the exception occurs in the m() method – ArithmeticException where it is not handled, so it is propagated to the previous n() method where it is not handled, again it is propagated to the p() method where the exception is handled.


Example 28

public class ExceptionHandlingDemo {

	public static void main(String args[]) {
		try {
			int i, sum;
			sum = 10;
			for (i = -1; i < 3; ++i)
				sum = (sum / i);
		} catch (ArithmeticException e) {
			System.out.print("0");
		}
		System.out.print(sum);
	}
}

Here, the value of the variable sum is printed outside of the try block, the sum is declared only in the try block, and outside try block it is undefined.


Example 29

public class ExceptionHandlingDemo {

	public static void main(String args[]) {
		try {
			String str = "beginnersbook";
			System.out.println(str.length());
			char c = str.charAt(0);
			c = str.charAt(40);
			System.out.println(c);
		} catch (StringIndexOutOfBoundsException e) {
			System.out.println("StringIndexOutOfBoundsException!!");
		}
	}
}

Here, an exception occurred because the referenced index was not present in the String.


Example 30

public class ExceptionHandlingDemo {

    public static void main(String[] args) {

            try {
                int num = Integer.parseInt("XYZ");
                System.out.println(num);
            } catch (StringIndexOutOfBoundsException e) {
                System.out.println("String IndexOutOfBounds Exception occurred!!");
            } catch (NumberFormatException e) {
                System.out.println("Number format exception occurred");
            } catch (Exception e) {
                System.out.println("Exception occurred");
            }
        }
    }

Here, an exception is not of type StringIndexOutOfBounds, so moved to the next catch where the exception is handled.

Throw in Java

HOME

In Java we have already defined exception classes such as ArithmeticException, NullPointerException, ArrayIndexOutOfBounds exception etc. These exceptions are set to trigger on different conditions. For example when we divide a number by zero, this triggers ArithmeticException, when we try to access the array element out of its bounds then we get ArrayIndexOutOfBoundsException.


The Java throw keyword is used to throw an exception explicitly. We specify the exception object which is to be thrown. The Exception has some message with it that provides the error description. These exceptions may be related to user inputs, server, etc.

We can throw either checked or unchecked exceptions in Java by throw keyword. It is mainly used to throw a custom exception.

throw Instance
Example:
throw new ArithmeticException("/ by zero");

Instance must be of type Throwable or a subclass of Throwable. For example Exception is a sub-class of Throwable and user defined exceptions typically extend Exception class.Data types such as int, char, floats or non-throwable classes cannot be used as exceptions.

The flow of execution of the program stops immediately after the throw statement is executed and the nearest enclosing try block is checked to see if it has a catch statement that matches the type of exception. If it finds a match, controlled is transferred to that statement otherwise next enclosing try block is checked and so on. If no matching catch is found then the default exception handler will halt the program.

public class Example1 {

	public static void test() {
		try {
			throw new ArithmeticException(" Hello ");
		} catch (ArithmeticException e) {
			System.out.println("Caught throw exception in method.");
			throw e; // rethrowing the exception
		}
	}

	public static void main(String args[]) {
		try {
			test();
		} catch (ArithmeticException e) {
			System.out.println("Caught exception in main.");
		}
	}
}

Output
Caught throw exception in method.
Caught exception in main.

Let us take another example where we have created the validate method that takes integer value as a parameter. If the age is less than 18, we are throwing the ArithmeticException otherwise print a message “Person is eligible to drive!!” .

public class Example1 {

	public static void validate(int age) {
		if (age < 18) {

			// throw Arithmetic exception if not eligible to drive
			throw new ArithmeticException("Person is not eligible to drive");
		} else {
			System.out.println("Person is eligible to drive!!");
		}
	}

	public static void main(String args[]) {
		validate(13);

	}
}

Exception in thread "main" java.lang.ArithmeticException: Person is not eligible to drive
	at ExceptionsExamples.Example1.validate(Example1.java:9)
	at ExceptionsExamples.Example1.main(Example1.java:16)

We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!

Throws in Java

HOME

The throws keyword in Java is used in the signature of method to indicate that this method might throw one of the listed type of exceptions. The caller to these methods has to handle the exception using a try-catch block.

Syntax of throws

return_type method_name() throws ExceptionType1, ExceptionType2 …{  
//method code  
} 

As you can see from the above syntax, we can use throws to declare multiple exceptions.

Below is an example of throws exception. Here, as you can see IOException is listed as an exception. This exception is handled by a try catch block when findFile() method is called.

public class ThrowsExample {

	public static void findFile() throws IOException {

		File file= new File("C:\\test.txt");
		FileInputStream stream = new FileInputStream(file);

	}

	public static void main(String[] args) {
		try {
			findFile();
		} catch (IOException e) {
			System.out.println(e);
		}
	}
}

Output
java.io.FileNotFoundException: C:\test.txt (The system cannot find the file specified)

When we run this program, if the file test.txt does not exist, FileInputStream throws a FileNotFoundException which extends the IOException class.

If a method does not handle exceptions, the type of exceptions that may occur within it must be specified in the throws clause so that methods further up in the call stack can handle them or specify them using throws keyword themselves.

The findFile() method specifies that an IOException can be thrown. The main() method calls this method and handles the exception if it is thrown.

In a program, if there is a chance of raising an exception then compiler always warn us about it and compulsorily we should handle that checked exception, Otherwise we will get compile time error saying unreported exception XXX must be caught or declared to be thrown. To prevent this compile time error we can handle the exception in two ways: 

  1. We have caught the exception i.e. we have handled the exception using try/catch block.
  2. We have declared the exception i.e. specified throws keyword with the method.

Case 1 : Handle Exception Using try-catch block

In case we handle the exception, the code will be executed fine whether exception occurs during the program or not.

class Demo {
	void method() throws IOException {
		throw new IOException("IOException Occurred");
	}
}

public class TestThrowsExample2 {

	public static void main(String[] args) {
		try {
			Demo demo = new Demo();
			demo.method();
		} catch (Exception e) {
			System.out.println("Exception handled");
		}

		System.out.println("Continue the program...");
	}
}

Output
Exception handled
Continue the program...

Case 2: We declare the exception, if exception does not occur, the code will be executed fine.

class Test {
	void method() throws IOException {
		System.out.println("No Exception");
	}
}

public class TestThrowsExample3 {

	public static void main(String[] args) {
		try {
			Test test = new Test();
			test.method();
		} catch (Exception e) {
			System.out.println("Exception handled");
		}

		System.out.println("Continue the program...");
	}
}

Output
No Exception
Continue the program...

Case 3 :  We declare the exception and the exception occurs, it will be thrown at runtime because throws does not handle the exception.

class TestDemo {
	void method() throws IOException {
		throw new IOException("IOException Occurred");
	}
}

public class TestThrowsExample4 {

	public static void main(String[] args) throws IOException {
		TestDemo test = new TestDemo();
		test.method();
		System.out.println("Continue the program...");

	}

}

Output
Exception in thread "main" java.io.IOException: IOException Occurred

Multiple Catch Exceptions

HOME

In the previous tutorial, I have explained about the control flow of try catch and finally blocks in Java. In this tutorial, I’ll explain multiple catch exceptions. Java supports multiple catch exceptions, that means a try block can have more than one catch handlers. All catch blocks must be ordered from most specific to most general, i.e. catch for ArithmeticException must come before catch for Exception.

Scenario 1 In the below example, an array is defined of size 10 and we want to perform an invalid arithmetic operation on element 15 of the array. In this case, we have defined 3 different catch handlers to handle the exception – Arithmetic Exception, ArrayIndexOutOfBounds Exception and Parent Exception. The try block has thrown exception – Arithmetic as the Arithmetic operation is invalid (divide by 0).

public class MultipleCatchDemo1 {

	public static void main(String[] args) {
		try {
			int a[] = new int[10];
			a[15] = 30 / 0;
		
        } catch (ArithmeticException e) {
			System.out.println("Arithmetic Exception occurs");
		
        } catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("ArrayIndexOutOfBounds Exception occurs");
		
        } catch (Exception e) {
			System.out.println("Parent Exception occurs");
		
        }
		System.out.println("Rest of the program");
	}
}

Scenario 2 – In the below example, I’m throwing an exception which is not handled by first catch exception handler.

public class MultipleCatchDemo2 {

	public static void main(String[] args) {

		try {
			int a[] = new int[10];
			System.out.println(a[15]);

		} catch (ArithmeticException e) {
			System.out.println("Arithmetic Exception occurs");

		} catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("ArrayIndexOutOfBounds Exception occurs");

		} catch (Exception e) {
			System.out.println("Parent Exception occurs");

		}
		System.out.println("Rest of the program");
	}
}

Scenario 3 – In the below example, I’m throwing an exception which is not handled by any catch exception handler specified in the program. Then, parent exception handler will be invoked.

public class MultipleCatchDemo3 {

	public static void main(String[] args) {
		try {
			int a[] = new int[10];
			System.out.println(a[10]);

		} catch (ArithmeticException e) {
			System.out.println("Arithmetic Exception occurs");
		
		} catch (NullPointerException e) {
			System.out.println("NullPointer Exception occurs");
		
		} catch (Exception e) {
			System.out.println("Parent Exception occurs");
		
		}
		System.out.println("Rest of the program");
	}
}

Scenario 4 – In the below example, we do not maintain the order of preference in exceptions (child to parent), then compile time error occurs.

public class MultipleCatchDemo4 {

	public static void main(String[] args) {
		try {
			int a[] = new int[10];
			System.out.println(a[10]);

		} catch (Exception e) {
			System.out.println("Parent Exception occurs");

		} catch (ArithmeticException e) {
			System.out.println("Arithmetic Exception occurs");

		} catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("ArrayIndexOutOfBounds Exception occurs");

		}
		System.out.println("Rest of the program");
	}
}

Scenario 5 – In the below example, try block has 2 exceptions. It will call the first suitable catch block for the first try statement which has thrown the exception.

public class MultipleCatchDemo5 {

	public static void main(String[] args) {
		try {
			int a[] = new int[10];
			a[15] = 30 / 0;
			System.out.println(a[20]);

		} catch (ArithmeticException e) {
			System.out.println("Arithmetic Exception occurs");

		} catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("ArrayIndexOutOfBounds Exception occurs");

		} catch (Exception e) {
			System.out.println("Parent Exception occurs");

		}
		System.out.println("Rest of the program");
	}
}

Similarly, if I interchanged the try statements as shown below the response will also changes.

public class MultipleCatchDemo6 {

	public static void main(String[] args) {
		try {
			int a[] = new int[10];
			System.out.println(a[20]);
			a[15] = 30 / 0;

		} catch (ArithmeticException e) {
			System.out.println("Arithmetic Exception occurs");

		} catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("ArrayIndexOutOfBounds Exception occurs");

		} catch (Exception e) {
			System.out.println("Parent Exception occurs");

		}
		System.out.println("Rest of the program");
	}
}

Flow control in try catch finally in Java

HOME

In this tutorial, I’ll explain about the flow control of try catch and finally blocks in accordance to the exception.

What is try block in Java?

It is used to specify a block where we should place exception code. The try block must be followed by either catch or finally. It means, we can’t use try block alone.
If an exception occurs at the particular statement of try block, the rest of the block code will not execute. So, it is recommended not to keeping the code in try block that will not throw an exception.

What is catch block in Java?

It is used to handle the exception by declaring the type of exception within the parameter. It must be preceded by try block which means we can’t use catch block alone. It can be followed by finally block later.
You can use multiple catch block with a single try block.

What is finally block in Java?

It is used to execute important statements such as establishing connection, stream, etc. It is always executed whether exception is handled or not.

Syntax of try-catch block

try{
//throw an exception
}catch{ //handle exception }

Syntax of try-catch-finally block

try{
//throw an exception
}catch { //handle exception }
finally { //important code which will always be executed  }

1.Exception occurs in try block and handled in catch block

If a statement in try block throws an exception, then rest of the code of try block is not executed. The control transfers to corresponding catch block. After the execution of code in catch block, the control moves to the rest of the program code to be executed.

public class TryCatchDemo {

	public static void main(String[] args) {
		{
			try {
				String a = null; // null value
				System.out.println(a.length());

				// This will never execute as try block has exception just above this statement
				System.out.println("Inside try block");

				// Exception will be handled in catch block and will execute the statements in
				// catch block
			} catch (NullPointerException e) {
				System.out.println("NullPointer Exception - Exception caught in Catch block");

			}

			// Rest of the program will be executed
			System.out.println("Outside try-catch block");
		}
	}
}

Output
NullPointer Exception - Exception caught in Catch block
Outside try-catch block

2. Exception occurs in try block and handled in catch block and finally block is present

If a statement in try block throws an exception, then rest of the code of try block is not executed. The control transfers to corresponding catch block. After the execution of code in catch block, the control moves to finally block (if present) and then the rest of the program is executed.

public class TryCatchFinallyDemo {

	public static void main(String[] args) {
		{
			try {
				String a = null; // null value
				System.out.println(a.length());

				// This will never execute as try block has exception just above this statement
				System.out.println("Inside try block");

				// Exception will be handled in catch block and will execute the statements in
				// catch block
			} catch (NullPointerException e) {
				System.out.println("NullPointer Exception - Exception caught in Catch block");

				// Statement present in finally block will be executed irrespective whether
				// exception is handled or not
			} finally {
				System.out.println("finally block executed");
			}

			// Rest of the program will be executed
			System.out.println("Outside try-catch block");
		}
	}
}

Output
NullPointer Exception - Exception caught in Catch block
finally block executed
Outside try-catch block

3. Exception occurred in try-block is not handled in catch block without finally block

If a statement in try block throws an exception, then rest of the code of try block is not executed.

public class TryNoCatchDemo {

	public static void main(String[] args) {
		{
			try {
				String a = null; // null value
				System.out.println(a.length());

				// This will never execute as try block has exception just above this statement
				System.out.println("Inside try block");

				// Incorrect Exception
			} catch (IndexOutOfBoundException e) {
				System.out.println("IndexOutOfBound Exception - Exception caught in Catch block");

			}


			// Rest of the program will be executed
			System.out.println("Outside try-catch block");
		}
	}
}

Output
Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	IndexOutOfBoundException cannot be resolved to a type

	at JavaDemo.Exception.TryNoCatchDemo.main(TryNoCatchDemo.java:15)

4. Exception occurred in try-block is not handled in catch block with finally block

public class TryNoCatchFinallyDemo {

	public static void main(String[] args) {
		{
			try {
				String a = null; // null value
				System.out.println(a.length());

				// This will never execute as try block has exception just above this statement
				System.out.println("Inside try block");

				// Incorrect Exception
			} catch (IndexOutOfBoundException e) {
				System.out.println("IndexOutOfBound Exception - Exception caught in Catch block");

			}

			finally {
				System.out.println("finally block executed");
			}

			// Rest of the program will be executed
			System.out.println("Outside try-catch block");
		}
	}
}

Output
Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	IndexOutOfBoundException cannot be resolved to a type

	at JavaDemo.Exception.TryNoCatchDemo.main(TryNoCatchDemo.java:15)

5. Exception doesn’t occur in try-block

If a statement in try block does not throw an exception, then catch block will be never executed and then rest of the program will be executed.

public class NoTryCatchDemo {

	public static void main(String[] args) {
		try {

			String str = "123";

			int num = Integer.parseInt(str);

			// this statement will execute
			// as no any exception is raised by above statement
			System.out.println("Inside try block");

		}

		catch (NumberFormatException ex) {

			System.out.println("catch block executed.");

		}

		System.out.println("Outside try-catch clause");
	}
}

Output
Inside try block
Outside try-catch clause

6. Exception doesn’t occur in try-block with finally block

If a statement in try block does not throw an exception, then catch block will never be executed. But the finally block will be executed and then rest of the program will be executed.

public class NoTryCatchFinallyDemo {

	public static void main(String[] args) {
		try {

			String str = "123";

			int num = Integer.parseInt(str);

			// this statement will execute
			// as no any exception is raised by above statement
			System.out.println("Inside try block");

		}

		catch (NumberFormatException ex) {

			System.out.println("catch block executed");

		} finally {
			System.out.println("finally block executed");
		}

		System.out.println("Outside try-catch clause");
	}
}

Output
Inside try block
finally block executed
Outside try-catch clause

Java Exceptions Tutorial: Built-in and User-defined Exceptions

HOME

Table of Contents

  1. These are exceptions that are checked at compile-time.
  2. They must be either handled using a try-catch block or declared in the method signature using the `throws` keyword.
  3. Examples include IOException, SQLException, and FileNotFoundException.

It is thrown when an exception has occurred in an arithmetic operation. Below is an example of this exception.

public class ArithmeticExceptionDemo {

	public static void main(String[] args) {
		{
			try {
				int a = 30, b = 0;
				int c = a / b; // cannot divide by zero
				System.out.println("Result = " + c);
			} catch (ArithmeticException e) {
				System.out.println("Can't divide a number by 0");
			}
		}
	}
}

2. ArrayIndexOutOfBoundsException

It is thrown when an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.

public class ArrayIndexOutOfBoundsExceptionDemo {

	public static void main(String[] args) {
		{
			try {
				// Create an array of size 5
				int a[] = new int[5];

				// Access 11th element from array of size 5
				a[10] = 9;
			} catch (ArrayIndexOutOfBoundsException e) {
				System.out.println("Array Index is Out Of Bounds");
			}
		}
	}
}

3. StringIndexOutOfBoundsException

It is thrown by String class methods to indicate that an index is either negative or greater than the size of the string.

public class StringOutOfBoundDemo {

	public static void main(String[] args) {
		{
			try {
				String a = "This is testing"; // length is 15
				System.out.println("Length of String :" + a.length());

				char b = a.charAt(20); // accessing 20th element
				System.out.println(b);
			} catch (StringIndexOutOfBoundsException e) {
				System.out.println("StringIndexOutOfBoundsException");
			}
		}
	}
}

4. NullPointerException

This exception is thrown when referring to the members of a null object.

public class NullPointerDemo {

	public static void main(String[] args) {
		{
			try {
				String a = null; // null value
				System.out.println(a.length());
			} catch (NullPointerException e) {
				System.out.println("NullPointerException");
			}
		}
	}
}

5. NumberFormatException

This exception is thrown when a method can not convert a string into a numeric format.

public class NumberFormatDemo {

	public static void main(String[] args) {
		try {
			// "java" is not a number
			int num = Integer.parseInt("java");

			System.out.println(num);
		} catch (NumberFormatException e) {
			System.out.println("Number format exception");
		}
	}
}

6. FileNotFoundException

This Exception is thrown when a file is not accessible or does not open.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;

public class FileNotFoundDemo {

	public static void main(String[] args) {
		try {

			// Following file does not exist
			File file = new File("C://demofile.txt");

			FileReader fr = new FileReader(file);
		} catch (FileNotFoundException e) {
			System.out.println("File does not exist");
		}
	}
}

7. ClassNotFoundException

This Exception is raised when we try to access a class whose definition is not found.

package JavaDemo;

public class ClassNotFoundExceptionDemo {

	public static void main(String[] args) {
		try {
			Class temp = Class.forName("gfg");
			// Calling the clas gfg which is not present in the
			// current class temp instance of calling class it
			// will throw ClassNotFoundException;
		} catch (ClassNotFoundException e) {
			// block executes when mention exception occur
			System.out.println("Class does not exist check the name of the class");
		}
	}
}

8. IOException

It is thrown when an input-output operation failed or interrupted.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class IOExceptionDemo {

	public static void main(String[] args) {

		String filepath = "C:\\Users\\Desktop\\IOTest1.txt";
		BufferedReader br1 = null;
		String curline;

		try {
			br1 = new BufferedReader(new FileReader(filepath));

			while ((curline = br1.readLine()) != null) {
				System.out.println(curline);
			}
		} catch (IOException e) {
			System.err.println("IOException found :" + e.getMessage());
		} finally {
			try {
				if (br1 != null)
					br1.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

9. NoSuchMethodException

It is thrown when accessing a method which is not found.

10. InterruptedException

It is thrown when a thread is waiting , sleeping , or doing some processing , and it is interrupted.

11. NoSuchFieldException

It is thrown when a class does not contain the field (or variable) specified.

12. RuntimeException

This represents any exception which occurs during runtime. They are ignored during compilation time. Such as logical bugs.

import java.util.Scanner;

public class RunTimeDemo {

	public static void main(String[] args) {
		// Reading user input
		Scanner input_dev = new Scanner(System.in);
		System.out.print("Enter your age in Numbers: ");
		int age1 = input_dev.nextInt();
		if (age1 > 20) {
			System.out.println("You can view the page");
		} else {
			System.out.println("You cannot view the page");
		}
	}
}

13. SQLException

This type of exception occurs while executing queries on a database related to the SQL syntax.

14. IllegalArgumentException

It is thrown when an inappropriate and incorrect argument is passed to the method. Suppose, a method does not allow null, but we are providing null as the parametr, then this exception is thrown.

Exception Handling in Java

HOME

What is Exception in Java?

An exception is an unwanted or unexpected event which occurs at the run time of the program, that leads to the disruption of the normal flow of execution of the program.

What is Exception Handling?

Exception Handling is a mechanism to handle runtime errors happen in the program such as ClassNotFoundException, IOException, SQLException, RemoteException, etc, which disruptes the normal execution of the program.

Suppose there are 6 statements in your program and there occurs an exception at statement 3, the rest of the code will not be executed i.e. statement 4 to 6 will not be executed. If we perform exception handling, the rest of the statement will be executed. That is why we use exception handling in Java.

What is the difference between Error and Exception?

Error: An Error indicates serious problem that a reasonable application should not try to catch. Error are used by the Java run-time system(JVM) to indicate errors having to do with the run-time environment itself(JRE) or StackOverflowError or OutOfMemoryError

Exception: Exception indicates conditions that a reasonable application might try to catch. Example of exceptions are IOException, SQLException, etc.

Types of Exceptions

1) Checked Exception
The classes which directly inherit Throwable class except RuntimeException and Error are known as checked exceptions e.g. IOException, SQLException etc. Checked exceptions are checked at compile-time.

2) Unchecked Exception
The classes which inherit RuntimeException are known as unchecked exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-time, but they are checked at runtime.

Hierarchy of Java Exception classes

Keywords used in Exception Handling in Java

1. try keyword – It is used to specify a block where we should place exception code. The try block must be followed by either catch or finally. It means, we can’t use try block alone.

2. catch keyword – It is used to handle the exception. It must be preceded by try block which means we can’t use catch block alone. It can be followed by finally block later.

3. finally keyword – It is used to execute the important code of the program irrespective the exception is handled or not.

4. throw keyword – It is used to throw an exception explicitly in the program inside a function or inside a block of code.

5. throws keyword – It is used to declare exceptions. It doesn’t throw an exception. It specifies that there may occur an exception in the method. It is always used with method signature.

Exception Handling Example in Java

Let’s see an example of exception handling where we can use try-catch block and will not use try-catch statements. Below example shows an exception without try-catch block.

package JavaDemo;

public class ExceptionHandlingDemo {

	static String a = null;

	public static void main(String[] args) {

		System.out.println(a.length());
	}

}

Output
Exception in thread "main" java.lang.NullPointerException
	at JavaDemo.ExceptionHandlingDemo.main(ExceptionHandlingDemo.java:9)

Below example shows an exception with try-catch block.

package JavaDemo;

public class ExceptionHandlingDemo {
	static String a = null;

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		try {
			System.out.println(a.length());
		} catch (NullPointerException e) {
			System.out.println(e);
		}
		System.out.println("Exception is handled");
	}

}

Output
java.lang.NullPointerException
Exception is handled

Testing of SpringBoot Exception Handling

HOME

In the previous tutorial, I explained about the Testing of SpringBoot POST Method. In this tutorial, I will discuss the Testing of Exceptions in the SpringBoot application.

Response Statuses for Errors

The most commonly used error codes in SpringBoot Application are:-

  • 404 – RESOURCE NOT FOUND
  • 400 – BAD REQUEST
  • 401 – UNAUTHORIZED
  • 415 – UNSUPPORTED TYPE – Representation not supported for the resource
  • 500 – SERVER ERROR

Default Exception Handling with Spring Boot

Spring Boot provides a good default implementation for exception handling for RESTful Services.

This is the response when you try getting details of a non-existing student. You can see that the response status is 500 – Internal Server Error.

Customizing Exception Handling with Spring Boot

There are 2 most commonly used annotations used in Error Handling – @ExceptionHandler and @ControllerAdvice.

What is ExceptionHandler?

The @ExceptionHandler is an annotation used to handle the specific exceptions and send the custom responses to the client.

@ExceptionHandler(StudentNotFoundException.class)


What is ControllerAdvice?

A controller advice allows you to use exactly the same exception-handling techniques but apply them across the whole application, not just to an individual controller.

A combination of Spring and Spring Boot provides multiple options to customize responses for errors.

@ControllerAdvice
@RestController
public class CustomizedResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

You can specify the Response Status for a specific exception along with the definition of the Exception with the ‘@ResponseStatus’ annotation.

@ResponseStatus(HttpStatus.NOT_FOUND)

I have defined the StudentNotFoundExceptionclass. This Exception will be thrown by the controller when no resource i.e. Student to be returned in our case is found with HTTP Status of NOT_FOUND (404).

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(HttpStatus.NOT_FOUND)
public class StudentNotFoundException extends RuntimeException {

	public StudentNotFoundException(String exception) {
		super(exception);
	}
}

Now the response will be 404 – Not Found

{
    "timestamp": "2021-02-22T15:56:59.494+00:00",
    "status": 404,
    "error": "Not Found",
    "trace": "StudentNotFoundException: id-100,
    "message": "id-100",
    "path": "/students/100"
}

Customizing Error Response Structure

The default error response provided by Spring Boot contains all the details that are typically needed.

However, you might want to create a framework-independent response structure for your organization. In that case, you can define a specific error response structure.

import java.util.Date;

public class ExceptionResponse {
	private Date timestamp;
	private String message;
	private String details;

	public ExceptionResponse(Date timestamp, String message, String details) {
		super();
		this.timestamp = timestamp;
		this.message = message;
		this.details = details;
	}

	public Date getTimestamp() {
		return timestamp;
	}

	public String getMessage() {
		return message;
	}

	public String getDetails() {
		return details;
	}
}

To use ExceptionResponse to return the error response, let’s define a ControllerAdvice as shown below.

@ControllerAdvice
@RestController
public class CustomizedResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

	@ExceptionHandler(StudentNotFoundException.class)
	public final ResponseEntity<Object> handleUserNotFoundException(StudentNotFoundException ex, WebRequest request) {
		ExceptionResponse exceptionResponse = new ExceptionResponse(new Date(), ex.getMessage(),
				request.getDescription(false));
		return new ResponseEntity(exceptionResponse, HttpStatus.NOT_FOUND);
	}

Scenario 1-  How to execute a Get Request Method with an Invalid URL using Postman

The above scenario can be tested in the below way.

Feature: Student Exception

   @InvalidURL
   Scenario: Send a valid Request to create a student

    Given I send a request to the invalid URL "/students/100" to get a student details
    Then the response will return status of 404 and message "id-100"

Test Code to test the above scenario (StepDefinition file)

@SpringBootTest(classes = SpringBootRestServiceApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT)
public class CustomizedErrorsDefinition {

	private final static String BASE_URI = "http://localhost";

	@LocalServerPort
	private int port;

	private ValidatableResponse validatableResponse;

	private void configureRestAssured() {

		RestAssured.baseURI = BASE_URI;
		RestAssured.port = port;
	}

	protected RequestSpecification getAnonymousRequest() throws NoSuchAlgorithmException {
		configureRestAssured();
		return given();
	}

	@Given("^I send a request to the invalid URL \"([^\"]*)\" to get a student details$")
	public void iSendARequest(String endpoint) throws Throwable {

		validatableResponse = getAnonymousRequest().contentType(ContentType.JSON).when().get(endpoint).then();
	}

	@Then("^the response will return status of (\\d+) and message \"([^\"]*)\"$")
	public void extractResponse(int status, String message) {		validatableResponse.assertThat().statusCode(equalTo(status)).body("message", equalTo(message));
	}
}

To know more about SpringBootTest, refer to the tutorial on Integration Testing of SpringBoot.

@SpringBootTest(classes = SpringBootRestServiceApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT)

To know about all the dependencies we need to add to pom.xml to run the SpringBoot Test, refer to the tutorial about Testing of SpringBoot REST Application using Serenity BDD and Rest Assured for GET Method.

To know how you can test a SpringBoot Application in BDD format using Serenity, refer to the tutorial related to Serenity BDD with Cucumber for SpringBoot application.

The next tutorial explains the Testing of SpringBoot Validation for RESTful Services.