EXCEPTION HANDLING
C.SAGANA
AP(SrG)/CSE
Exception
• unwanted or unexpected event, which occurs
during the execution of a program
or
• event that disrupts the normal flow of the
program. It is an object which is thrown at
runtime
Exception Handling
• handle the runtime errors
• exception handling is managed via five keywords:
• try, catch, throw, throws, and finally
• Try
– Program statements need to be monitored for exception should be placed in
try block
– must be followed by either catch or finally
• Catch
– Catch the thrown exception and handle them
• Throw
– Throws the exceptions occurred
• Throws
– Used in methods, that does not use try, catch
• Finally
– Code that should be executed after try/catch should be written in finally block
– executed whether an exception is handled or not.
Syntax
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
}
Advantage of Exception Handling
• maintain the normal flow of the application
• Example
statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;
• Exception at statement 5, the rest of the code will not be executed
• perform exception handling, the rest of the statement will be
executed
Exception Types
• All exception types are
subclasses of the built-in class
Throwable
• Throwable has two subclasses
• Exception class is used for
exceptional conditions that user
programs should catch
• subclass of Exception called
RuntimeException
• Errors are abnormal conditions
that happen in case of severe
failures, these are not handled
by the Java programs
Uncaught Exceptions
• see what happens when you don’t handle Exceptions
class Exc0
{
public static void main(String args[])
{
int d = 0;
int a = 42 / d;
}
}
• exception generated when this example is executed:
• java.lang.ArithmeticException: / by zero
• at Exc0.main(Exc0.java:4)
try-catch block
• enclose the code that might throw an
exception
• Syntax
try
{
//code that may throw an exception
}
catch(Exception_class_Name ref) {} or finally{}
Using try and catch
class Exc2
{
public static void main(String args[])
{
int d, a;
try
{ // monitor a block of code.
d = 0; // no throw statement needed since built in exception
a = 42 / d; //may throw exception
System.out.println(“hello”); // will not be executed since exception occurs in
previous statement
}
catch (ArithmeticException e) //handling the exception
{ // catch divide-by-zero error
System.out.println("Division by zero.");
System.out.println(e);
}
System.out.println("After catch statement.");
}
Multi-catch block
• try block can be followed by one or more catch
blocks
• catch block must contain a different exception
handler
• At a time only one exception occurs and at a
time only one catch block is executed.
• All catch blocks must be ordered
• Eg: catch for ArithmeticException must come
before catch for Exception.
Multiple catch Clauses
class MultipleCatches
{
public static void main(String args[])
{
int a=5,b=0, c;
int d[]={1,2,3,4,5};
try
{
c=a/b;
for(int i=0;i<=5;i++)
{
System.out.println(d[i]);
}
}
catch(ArithmeticException e)
{
System.out.println("Divide by 0: " + e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index oob: " + e);
}
Ordering of catch while using multiple catch
class
• When multiple catch statements is used, exception
subclasses must come before any of their superclasses.
• catch statement that calls a superclass catch
exceptions, So that subclass would never be reached if
it came after its superclass
• Unreachable code is an error in java
• Example
• ArithmeticException is a subclass of Exception
• To fix the problem, reverse the order of the catch
statements.
class MultipleCatches
{
public static void main(String args[])
{
int a=5,b=0
int d[]={1,2,3,4,5};
try
{
c=a/b;
for(int i=0;i<=5;i++)
{
System.out.println(d[i]);
}
}
catch(Exception e)
{
System.out.println("Generic Exception catch.");
}
catch(ArithmeticException e)
{
System.out.println("Divide by 0: " + e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
}
}
Java’s Built-in Exceptions
• Inside the standard package java.lang
• RuntimeException called unchecked
exceptions
• compiler does not check to see if a method
handles or throws these exceptions
• unchecked exceptions defined in java.lang are
listed in below Table
checked exceptions
compiler expects exceptions to be thrown by a
method and does not handle it itself
Common Scenarios of Java Exceptions
1.int a=50/0;//ArithmeticException
2.String s=null;
System.out.println(s.length());//
NullPointerException
3. String s="abc";
int i=Integer.parseInt(s);//
NumberFormatException
4. int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException
Nested try block
• try block within a try block is known as nested try block
try
{
statement 1; statement 2;
try
{
statement 1; statement 2;
}
catch(Exception e)
{ }
}
catch(Exception e)
{ }
Example
class Excep6{
public static void main(String args[]){
try{
try{
System.out.println("going to divide");
int b =39/0;
}
catch(ArithmeticException e)
{ System.out.println(e);}
try{
int a[]=new int[5];
a[5]=4;
}
catch(ArrayIndexOutOfBoundsException e)
{System.out.println(e);}
System.out.println("other statement);
}
catch(Exception e){System.out.println("handeled");}
System.out.println("normal flow..");
finally block
• used to execute important code
• always executed whether exception is handled or not
• follows try or catch block
• Example:
public class TestFinallyBlock2{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
throw exception
• used to explicitly throw an exception
• throw either checked or unchecked exception
in java by throw keyword.
• syntax :throw exception;
throws keyword
• used to declare an exception
• Syntax
return_type method_name() throws exception_
class_name
{
//method code
}
Throw Vs throws
• throw example
void m()
{
throw new ArithmeticException(“Hello");
}
throws example
void m()throws ArithmeticException
{
//method code
}
Custom Exception or user-defined exception
class InvalidAgeException extends Exception
{
public InvalidAgeException (String str)
{
super(str); // calling the constructor of parent Exception
}
}
public class TestCustomException1 // class that uses custom exception InvalidAgeException
{
static void validate (int age) throws InvalidAgeException {
if(age < 18){
throw new InvalidAgeException("age is not valid to vote"); // throw an object of user defined ex
ception }
else {
System.out.println("welcome to vote");
}
}
public static void main(String args[])
{
try
{
validate(13);
}
catch (InvalidAgeException ex)
{
System.out.println("Caught the exception");
System.out.println("Exception occured: " + ex);
}
System.out.println("rest of the code..."); Output:
}
}