Java Tutorial 22 – Exception
The following Java Video introduces the concept of Exception Handling.
Please be patient . Video will load in some time. If you still face issue viewing video click here
A Summary of the points covered in the above demonstration –
- An Exception is a run-time error which interrupts the normal flow of program execution.
- A robust program should handle all exceptions and continue with its normal flow of program execution.
- Exception Handler is a set of code that handles an exception.
Exceptions can be handled in Java using try & catch.
Sytanx for using try & catch
try{
statement(s)
}
catch (exceptiontype name){
statement(s)
}
Step 1) Copy the following code into an editor
class JavaException {
public static void main(String args[]){
int d = 0;
int n =20;
int fraction = n/d;
System.out.println(“End Of Main”);
}
}
Step 2) Save the file & compile the code. Run the program using command, java JavaException.
Step 3) An Arithmetic Exception – divide by zero is shown as below for line # 5 and line # 6 is never executed.

Step 4) Now lets see examine how try and catch will help us handle this exception. We will put the exception causing line of code into a try block , followed by a catch block. Copy the following code into editor.
class JavaException {
public static void main(String args[]){
int d = 0;
int n =20;
try{
int fraction = n/d;
System.out.println("This line will not be Executed");
}
catch(ArithmeticException e){
System.out.println("In the catch clock due to Exception = "+e);
}
System.out.println("End Of Main");
}
}
Step 5) Save , Compile & Run the code.You will get the following output

As you observe , the exception is handled and the last line of code is also excucuted. Also note that Line # 7 will not be executed becasue as soon as an exception is rasied flow of control jumps to the catch block .
Note:
The AirtmeticException Object “e” carries information about the the exception that has occurred which can be useful in taking recovery actions.
FINALLY Block.
The finally block is executed irrespective of an exception being raised in the try block.It is optional to use with a try block.
try{
statement(s)
}
catch(ExceptiontType name){
statement(s)
}
finally{
statement(s)
}
In case, an exception is raised in the try block, finally block is executed after the catch block is executed.
Assignment
Step 1) Copy the following code into an editor.
class JavaException {
public static void main(String args[]){
try{
int d = 0;
int n =20;
int fraction = n/d;
}
catch(ArithmeticException e){
System.out.println("In the catch clock due to Exception = "+e);
}
finally{
System.out.println("Inside the finally block");
}
}
}
Step 2) Save , Compile & Run the Code.
Step 3) Expected output. Finally block is executed even though an exception is raised.
Step 4) Change the value of variable d = 1 . Save , Compile and Run the code and observe the output.
