0% found this document useful (0 votes)
61 views24 pages

CH 08 Exception Handling

The document discusses exception handling in programming. It defines exceptions as unexpected events that disrupt normal program execution. Common causes of exceptions include dividing by zero, file not found errors, and accessing arrays out of bounds. Exception classes are subclasses of the Exception class in the exception hierarchy. When an exception occurs, the runtime environment identifies the type and throws an exception object. Exception handling techniques include try-catch blocks to catch exceptions, the throw keyword to explicitly throw exceptions, and the throws keyword to indicate that a method may throw specific exceptions. Finally blocks are used to execute code regardless of whether an exception occurs.

Uploaded by

Tabassum Maktum
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
61 views24 pages

CH 08 Exception Handling

The document discusses exception handling in programming. It defines exceptions as unexpected events that disrupt normal program execution. Common causes of exceptions include dividing by zero, file not found errors, and accessing arrays out of bounds. Exception classes are subclasses of the Exception class in the exception hierarchy. When an exception occurs, the runtime environment identifies the type and throws an exception object. Exception handling techniques include try-catch blocks to catch exceptions, the throw keyword to explicitly throw exceptions, and the throws keyword to indicate that a method may throw specific exceptions. Finally blocks are used to execute code regardless of whether an exception occurs.

Uploaded by

Tabassum Maktum
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 24

Exception handling

Exception
are usually used to denote something unusual that
does not conform to the standard rules.

In programming, exceptions are events that arise due


to the occurrence of unexpected behaviour in certain
statements, disrupting the normal execution of a
program.

Exception is a run time error


Causes of Exception
Exceptions can arise due to a number of situations.
For example,
 Trying to access the 11th element of an array when the
array contains of only 10 element
(ArrayIndexOutOfBoundsException)
 Division by zero (ArithmeticException)
 Accessing a file which is not present
(FileNotFoundException)
 Failure of I/O operations (IOException)
 Illegal usage of null. (NullPointerException)
Exception Classes
Top class in exception hierarchy is Throwable

This class has two siblings: Error and Exception.

All the classes representing exceptional conditions


are subclasses of the Exception class.
Exception Hierarchy
What happens when an execution
occurs?
Runtime environment identifies the type of Exception
and throws the object of it.
If the method does not employ any exception
handling mechanism
 the exception is passed to the caller method, and so on.
If no exception handling mechanism is employed in
any of the Call Stack methods
 the runtime environment passes the exception object to the
default exception handler available with itself.
 The default handler prints the name of the exception along
with an explanatory message followed by stack trace at the
time the exception was thrown and the program is
terminated.
Exception Example
class ExDemo class ExDemo
{ {
public static void main(String args[]) public static void main(String args[])
{ {
int a,b,c; try{
a=5; int a,b,c;
b=0; a=5;
c=a/b; b=0;
System.out.println(“c=“+c); c=a/b;
System.out.println(“end”); System.out.println(“c=“+c); }
} catch(Exception e) {
} System.out.println(“Error: “+e);
}
Successfully compiled but terminated at System.out.println(“end”);
}}
the time of execution
Successfully compiled and executed
Displays error message
Error: java.lang.ArithmeticException: / by
zero
end
Exception Handling Techniques

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.

You might also like