CH 08 Exception Handling
CH 08 Exception Handling
Exception
are usually used to denote something unusual that
does not conform to the standard rules.
try..catch
throw
throws
finally
try…catch
try/catch block can be placed within any method that
you feel can throw exceptions.
All the statements to be tried for exceptions are put in
a try block
catch block is used to catch any exception raised from
the try block.
If exception occurs in any statement in the try block
control immediately passes to the corresponding
catch block.
try…catch
Syntax
try
{
//statements to be monitored
}
catch(Exception_type ExOb)
{
//exception handling code
}
Exception Example
class ExDemo
{
public static void main(String args[])
{
try{
int a[]={10,20};
System.out.println(a[3]);
}
catch(Exception e)
{
System.out.println(“Error: “+e);
}
}
}
Output
Error: java.lang.ArrayIndexOutOfBoundsException: 3
try…with multiple catch
First write catch with subclass exception objects and then super class
object
Syntax
try
{
//statements to be monitored
}
catch(Exception_type ExOb1)
{
//exception handling code
}
catch(Exception_type ExOb2)
{
//exception handling code
}
Exception Example
class MultipleCatch Output
{ public static void main(String args[])
{ try{ java MultipleCatch abc
int p,q,r; Then Output
q=args.length; Error:
r=p/q; java.lang.ArrayIndexOutOfBoundsExceptio
System.out.println(r); n: 3
int a[]={10,20};
System.out.println(a[3]);
OR
}
catch(ArithmeticException e)
java MultipleCatch
{
System.out.println(“Error: “+e); Then Output
} Error: java.lang.ArithmeticException: / by
catch(ArrayIndexOutOfBoundsException e) zero
{
System.out.println(“Error: “+e);
}
}
}
finally
The finally block will execute whether or not an exception is
thrown.
If an exception is thrown, the finally block will execute even if
no catch statement matches the exception.
Any time a method is about to return to the caller from inside a
try/catch block, via an uncaught exception or an explicit return
statement, the finally clause is also executed just before the
method returns.
mandatory to execute statements like closing file handles,
releasing resources, etc. can be put in a finally block.
The finally clause is optional.
each try statement requires at least one catch or a finally clause.
finally
Syntax
try
{
//statements to be monitored
}
catch(Exception_type ExOb)
{
//exception handling code
}
finally
{
//anyway code to be executed
}
finally example
class FinallyDemo1
{ public static void main(String args[])
Output
Error: java.lang.ArithmeticException: / by
{ try
zero
{ int a,b,c;
finally executed
a=5;
b=0;
c=a/b;
System.out.println(c);
}
catch(ArithmeticException e)
{
System.out.println("Error: "+e);
}
finally
{
System.out.println("finally executed");
}
}}
finally example
class FinallyDemo catch(ArithmeticException e)
{ {
public static void main(String args[]) System.out.println("Error: "+e);
return 0;
{
}
A();
} finally
static int A() {
{ System.out.println("finally executed");
try }
}
{
}
int a,b,c;
a=5;
b=0; Output
c=a/b; Error: java.lang.ArithmeticException: / by
System.out.println(c); zero
return c; finally executed
}
throw keyword
used to explicitly throw an exception.
useful when we want to throw a user-
defined exception.
The syntax for throw keyword is as follows:
throw new ThrowableInstance;
For example
throw new NullPointerException();
throw example
class ThrowDemo
{
Output
public static void main(String args[]) Error:
{
java.lang.NumberFormatE
try
{ xception
throw new NumberFormatException();
}
catch(NumberFormatException e)
{
System.out.println("Error: "+e);
}
}
}
throws keyword
If a method is capable of causing an exception that it does not handle, it
must specify this behavior so that callers of the method can guard
themselves against that exception
is added to the method signature to let the caller know about what
exception the called method can throw.
responsibility of the caller to either handle the exception (using try…catch
mechanism) or it can also pass the exception (by specifying throws clause
in its method declaration).
If all the methods in a program pass the exception to their callers
(including main( )), then ultimately the exception passes to the default
exception handler.
syntax
type method-name(parameter-list) throws exception-list
{
// body of method
}
throws example
class ThrowsDemo {
public static void main(String args[])
Output
{ try Error:
{
java.lang.NumberFormatE
A();
} xception
catch(NumberFormatException e)
{
System.out.println("Error: "+e);
}
}
static void A() throws
NumberFormatException
{
throw new NumberFormatException();
}
}
User defined exception
Used to create our own exceptions
Just define a subclass of Exception class to create your own
exception
throw keyword is used to throw an exception
String toString()
is a method of Throwable class which Returns a String object containing a
description of the exception. This method is called by println( ) when
outputting a Throwable object.
Syntax
class exception_name extends Exception
{
public String toString()
{
//body of method
}
}
Creating your own exception
class MyException extends Exception { public static void main(String args[]) {
private int detail;
try {
MyException(int a) {
detail = a; compute(1);
} compute(20);
public String toString() { } catch (MyException e) {
return "MyException[" + detail + "]";
System.out.println("Caught " + e);
}
} }
class ExceptionDemo { }
static void compute(int a) throws MyException {
System.out.println("Called compute(" + a + ")"); Output
if(a > 10) Called compute(1)
throw new MyException(a); Normal exit
System.out.println("Normal exit"); Called compute(20)
} Caught MyException[20]
• Create our own exception to display
exception condition if number is odd. WAP
to throw that exception.