SAP

Must Learn!

Big Data

Web

In case there are multiple exceptions that might arise in a try block, you can provide several catch blocks each handling a different type of exception.

In this tutorial, you will learn-


Try Catch Syntax:-

try{
statement(s)
}
catch (exceptiontype name){
}
catch (exceptiontype name){
}
catch (exceptiontype name){
}
catch (exceptiontype name){
}

Java Exception class Hierachy

After one catch statement executes, the others are bypassed, and execution continues after the try/catch block.The nested catch blocks follow Exception hierarchy.

Guide to Java Exception Hierarchy

  • All exception classes in java extends the class ‘Throwable’. ‘Throwable’ has two sub classes, Error and Exception
  • The Error class defines the exception or the problems that are not expected to be occur under normal circumstances by our program, example Memory error, Hardware error , JVM error etc
  • • The Exception class represents the exceptions that can be handled by our program and our program can be recovered from this exception using try and catch block
  • Runtime exception is a sub-class of the exception class. Exception of these type represents exception that occur at the run time and which cannot be track at the compile time. A very good example of same is divide by zero exception, or null pointer exception etc
  • IO exception is generated during input and output operations
  • Interrupted exceptions in java, is generated during multiple threading.
Assignment: To understand nesting of try and catch blocks

Step 1)  Copy the following code into an editor

class JavaException {
	public static void main(String args[]){
	try{
		int d =1;
		int n =20;
		int fraction = n/d;
		int g[] ={1} ;
		g[20] =100;
		}
	/*catch(Exception e){
		System.out.println("In the catch clock due to Exception = "+e);
	}*/
	catch(ArithmeticException e){
		System.out.println("In the catch clock due to Exception = "+e);
	}
	catch(ArrayIndexOutOfBoundsException e){
		System.out.println("In the catch clock due to Exception = "+e);
	}
		System.out.println("End Of Main");
	}
}

Step 2)  Save the file  & compile the code. Run the program using command, java JavaException.


Step 3) An ArrayIndexOutOfBoundsException is generated. Change the value of int d to 0. Save ,Compile & Run the code.


Step 4)  An ArithmeticException must be generated.


Step 5) Uncomment line #10 to line #12 . Save , Compile & Run the code.


Step 6) Compilation Errror ? This is because Exception is the base class of ArithmeticException Exception. Any Exception that is raised by ArithmeticException can be handled by Exception class as well .So the catch block of ArithmeticException will never get a chance to be executed which makes it redundant. Hence the compilation error.

 

YOU MIGHT LIKE: