Chapter 7 Exception Handling
Chapter 7 Exception Handling
IN JAVA
Table of Contents
• Exception Handling Fundamentals
• Exception Types
• Uncaught Exception
• Using Try-Catch
• Multiple Catch Clauses
• Nested Try Statement
• Throw
• Throws
• Finally.
Introduction
• Error are the wrongs that make program go wrong.
• Error may produce an incorrect output or terminate program execution
abruptly or abnormally.
• Types of error:
• Compile Time Error: All Syntax related error. Eg: Missinf Semicolon,
undeclared variable, missing braces, etc.
• Run Time Error: Successfully creates a .class file but not run properly, as
a result, produces wrong result or may terminate abnormally. Eg: Divide by
zero, Accessing element out of bound, etc.
• Illustration of run time error, eg:
Class Error2
{ p.s.v.m(…..)
{ int a=10, b=5, c=5;
int x= a/(b-c); //Div. by Zero
SOP(“X= ”+X);
}
}
Error: java.lang.ArithmeticException: / by zero at Error2.main
• An Exception is a condition caused by run time error in a program. (It
leads to abnormal termination of program)
• Sample Program:
statement 1;
statement 2; //exception occurs
statement 3;
statement 4;
Then rest of the code (3-4) will not be executed.
try Block
Throws
exception Statement that causes an Exception Object
object exception Creator
Catch Block
Statement that handles the Exception Handler
exception
try
{ x= a/(b-c);
}
catch(ArithmeticException e)
{ SOP(“Div. By Zero…”); }
y = a / (b+c);
SOP(“Y = ” + Y);
}
}
Example of multiple catch blocks
Class error4
{ p.s.v.m(String args[])
{ int a[]={5,10}; int b= 5;
try
{ int x= a[1] / (b-a[0]); }
Output:
Div by Zero
catch (ArithmeticException e) Y=2
{ SOP(“Div. by Zero”); }
catch (ArrayIndexOutOfBoundException e)
{ SOP(“Array Index Error”); }
catch (ArrayStoreException e)
{ SOP(“Wrong Data Type”); }
int y= a[1] / a[0]; SOP(“Y = ” + y);
}
}NOTE: if exception not handled by code int y= a[1] / a[0] ;SOP(“Y = ” +
y); will not execute.
Example of Nested try statements
Class eg_nested_try
{ p.s.v.m(String args[])
{
try
{ int a=2, b=4, c=2, x=7, z;
int p[ ]= { 2 };
p[ 3 ]= 33;
try
{ z = x / ( (b*b)- (4 * a*c) ) ;
SOP(“Value z= “ + z);
}
catch( ArithmeticException e)
{ SOP(“Div. by Zero in Arithmetic Expression”); }
}
catch ( ArrayIndexOutOfBoundsException e)
{ SOP(“Array Index Out of Bound”); }
}
}
Java finally block
• Java finally block is a block that is used to
execute important code such as closing
connection, stream etc.
• Java finally block is always executed whether
exception is handled or not.
Java finally block
General form of exception-handling block
try
{ // block of code to monitor for errors
}
catch (ExceptionType1 exOb)
{ // exception handler for ExceptionType1
}
catch (ExceptionType2 exOb)
{ // exception handler for ExceptionType2
}
// ...
finally
{// block of code to be executed after try block ends
}
Finally block
class TestFinallyBlock1{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
} Output:
} finally block is always executed
Exception in thread main java.lang.ArithmeticException:/
by zero
throw clause(Un checked)
• The Java throw keyword is used to explicitly throw an
exception.
• We can throw either checked or uncheked exception in java
by throw keyword. The throw keyword is mainly used to
throw custom exception. We will see custom exceptions later.
• Syntax:
– throw exception object;
– Example:
• throw new IOException("sorry device error);
Exception Object
throw clause example
public class TestThrow1{
static void validate(int age){
try{
if(age<18)
throw new ArithmeticException("not valid");
else
Exception
System.out.println("welcome to vote");
created by our
} catch(ArithmeticException e){ sop(e);} program and
} thrown.
validate(13);
}
Output:
}
Exception in thread main java.lang.ArithmeticException:not valid
throws clause (Checked)
• The Java throws keyword is used to declare an exception. It
gives an information to the programmer that there may occur
an exception so it is better for the programmer to provide the
exception handling code so that normal flow can be
maintained.
• Syntax:
return_type method_name() throws exception_class_name{
//method code
}
throws clause
import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
Output:
}
} exception handled
public class Testthrows2{ normal flow...
public static void main(String args[]){
try{
M m=new M();
m.method();
}catch(Exception e){System.out.println("exception handled");}
System.out.println("normal flow...");
}
}
Difference between throw and throws
throw throws
Java throw keyword is used to Java throws keyword is used to declare an
explicitly throw an exception. exception.
Throw is used within the method. Throws is used with the method signature.
You cannot throw multiple exceptions. You can declare multiple exceptions e.g.
public void method()throws
IOException,SQLException.
User-defined exception
• Extending predefined Exception class to create
your own Exception.
• Syntax: throw new Throwable Subclass();
• Hierarchy:
Example of User Defined/own/ custom Exception
• If an exception occurs within the try block, it is thrown. Your code can
catch this exception (using catch) and handle it in some rational manner.
• Any code that absolutely must be executed after a try block completes is
put in a finally block.