Multiple questions on Exception Handling in Java

HOME

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

Example1

public class Example1 {

	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..");
	}
}

Output
Arithmetic Exception occurs
Continue the program..

Here, we have multiple catch blocks with a 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, now the program runs in normal flow.

Example2

public class Example2 {

	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..");
	}
}

Output
ArrayIndexOutOfBounds Exception occurs
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, now the program runs in normal flow.

Example3

public class Example3 {

	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, now the program runs in normal flow.

Example4

public class Example4 {

	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..");
	}
}

Output
Arithmetic Exception occurs
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 ArithmeticException. So, the catch block for ArithmeticException is executed. Once the corresponding catch block is executed, now the program runs in normal flow.

Example5

public class Example5 {

	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..");
	}
}
		

Output
Parent Exception occurs
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 Example6 {

	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..");
	}
}

Output
Unresolved compilation problems: 
Unreachable catch block for ArithmeticException. It is already handled by the catch block for Exception
Unreachable catch block for ArrayIndexOutOfBoundsException. It is already handled by the catch block for Exception

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

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

Output
Exception in thread "main" java.lang.ArithmeticException: / by zero

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 Example8 {

	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");
		}
	}
}

Output
Unresolved compilation problem: 
Unreachable catch block for ArrayIndexOutOfBoundsException. It is already handled by the catch block for Exception

Here, ArrayIndexOutOfBoundsException has been already caught by 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);
		}
	}
}

Output
a[1]=2
a[2]=3
a[3]=4
ArrayIndexOutOfBounds Exception occured

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

Example10

public class Example10 {

	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..");
	}
}

Output
going to divide by 0
java.lang.ArithmeticException: / by zero
java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
No more inner try catch block
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 Example11 {

	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 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");
		}
	}
}

Output
java.lang.ArithmeticException: / by zero
Outer 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 Example12 {

	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");
		}
	}
}

Output
Arithmetic exception
inner try block 1

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 Example13 {

	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 catch block is not executed. finally block is always executed irrespective the catch block is executed or not.

Example14

public class Example14 {

	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 ..");
	}
}

Output
Inside the try block
finally block is always executed
Exception in thread "main" java.lang.ArithmeticException: / by zero

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 Example15 {

	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 ..");
	}
}

Output
Inside try block
Exception is handled
java.lang.ArithmeticException: / by zero
finally block is always executed
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 Example16 {

	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");
		}
	}
}

Output
a = 0
Divide by zero error
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 Example17 {

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

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

}

Output
Exception in thread "main" java.lang.ArithmeticException: / by zero

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

Example 18

public class Example18 {

	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 catch block only to handle the exceptions.

Example 19

public class Example19 {

	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 ..");
	}
}

Output
Exception in thread "main" Welcome to the Admission process!!
java.lang.ArithmeticException: Student is not eligible for admission

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

Example 20

public class Example20 {

	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");
	}
}

Output
try - first statement
start - myMethod
An Exception
finally
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 Example21 {

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

Output
Unresolved compilation problems: 
No exception of type int can be thrown; an exception type must be a subclass of Throwable

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 Example22 {

	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 ");
		}
	}
}

Output
Unresolved compilation problems: 
No exception of type Test can be thrown; an exception type must be a subclass of Throwable

Example 23

class Base extends Exception {
}

class Derived extends Base {
}

public class Example23 {

	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");
		}
	}
}

Output
Unresolved compilation problem: 
Unreachable catch block for Derived. It is already handled by the catch block for Base

Example 24

public class Example24 {

	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) {
		Example24 object = new Example24();
		object.A();
		object.display();
	}

}

Output
abdec

‘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 Example25 {

	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[]) {
		Example25 obj = new Example25();
		obj.p();
		System.out.println("Continue the program..");
	}
}

Output
Exception Handled
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 Example26 {

	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[]) {
		Example26 obj = new Example26();
		obj.p();
		System.out.println("Continue the program..");
	}
}

Output
Unresolved compilation problem: 
Unhandled exception type IOException

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 supposed to be handled, but as it is checked Exception which can not be handled by Exception.

Example 27

public class Example27 {

	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[]) {
		Example27 obj = new Example27();
		obj.p();
		System.out.println("Continue the program..");
	}
}

Output
Exception handled
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 Example28 {

	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);
	}
}

Output
Unresolved compilation problem: 
sum cannot be resolved to a variable

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

Example 29

public class Example29 {

	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!!");
		}
	}
}

Output
13
StringIndexOutOfBoundsException!!

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

Example 30

public class Example30 {

	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");
			}
		}
	}
}

Output
Number format exception occurred

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

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s