Вы находитесь на странице: 1из 40

Unit 6 Exception Handling

Basic Java
Unit 6 Exception Handling

Pratian Technologies (India) Pvt. Ltd.


www.pratian.com

Copyright 2008 Pratian Technologies


www.pratian.com

Basic Java

Unit 6 Exception Handling

Error Handling in Conventional Languages


Exceptions
Exception Handling in Java

Topics

Exception Hierarchy
Throwable Class
Error and Exception
Types of Exceptions
Throwing Exceptions
Declaring Exceptions per Method
Catching Exception
Designing user-defined Exception classes

Method Overriding and Exceptions

Copyright 2008 Pratian Technologies


www.pratian.com

Basic Java

Unit 6 Exception Handling

Error Condition

Our applications should be built to survive error


conditions.
The program / module must handle the error situation
gracefully and not just terminate abruptly
What error are we talking about ?

Copyright 2008 Pratian Technologies


www.pratian.com

Basic Java

Unit 6 Exception Handling

Error Condition

An error is a condition due to which a program cannot


normally continue execution and needs to be abruptly
terminated.

Copyright 2008 Pratian Technologies


www.pratian.com

Basic Java

Unit 6 Exception Handling

Error handling in traditional languages

Traditional error handling methods include

Boolean functions (which return TRUE/FALSE).


Integer functions (returns 1 on error).
And other return arguments and special values.

int main () {
int res;
if (can_fail () == -1) {
cout << "Something failed!" << endl;
return 1;
}
if(div(10,0,res) == -1) {
cout << "Division by Zero!" << endl;
return 2;
}
return 0;
}
Copyright 2008 Pratian Technologies
www.pratian.com

Basic Java

Am
IsCan
Ierror
forced
I
understand
to
handling
receive
Is
what
done
my
the
went
code
in a
maintainabl
wrong
series
returning
with
of if
value
then
juste?
block?
from
the a
function?
return
value?

Unit 6 Exception Handling

Problems with traditional approach


Function can return only
one value & not details
of the error condition

Caller is not forced to


receive the value
returned by the function

Copyright 2008 Pratian Technologies


www.pratian.com

Basic Java

Multiple if-else leads to


cluttered code & is
difficult to maintain

Unit 6 Exception Handling

Exception handling in Java

Javas support for error handling is done through


Exceptions.

What is an Exception?

An exception is an event that occurs during the execution


of a program that disrupts the normal flow of instructions.
In the wake of such an event, the JVM creates an
exception object, that contains information about the error,
including its type and state of the program when the error
occurred.
Creating an exception object and notifying the caller of
the method is called throwing an exception.

Copyright 2008 Pratian Technologies


www.pratian.com

Basic Java

Unit 6 Exception Handling

Exception handling mechanism


Throws
exception

Method where
error occurred
Method Call

Looking for
appropriate handler

Main

Sample Listing: DivisionErrorDemo.java

Copyright 2008 Pratian Technologies


www.pratian.com

Basic Java

Unit 6 Exception Handling

Why use exceptions?

Exception handling provides the programmer with


many advantages over traditional error-handling
techniques:

Am
IsCan
Ierror
forced
I
understand
to
handling
handle
exceptions?
Is
Is
what
done
itmy
easy
went
code
in ato
maintainabl
understand
wrong
series of
and
if
where
then
how
e?
block?
when
to
anhandle
error is
exceptions?
thrown?

Copyright 2008 Pratian Technologies


www.pratian.com

Basic Java

Unit 6 Exception Handling

To summarize advantages of Exception


handling

Exception handling provides the programmer with


many advantages over traditional error-handling
techniques:

It provides a means to separate error-handling code from


functioning program code.
It provides a mechanism for propagating errors up the
method call stack, meaning that methods higher up the call
chain can be allowed to handle problems originating lower
in the chain.
It provides a way to organize and differentiate between
different types of abnormal conditions.
Both, application logic and problem handling logic, become
simpler, cleaner and clearer.

Copyright 2008 Pratian Technologies


www.pratian.com

Basic Java

Unit 6 Exception Handling

Throwable class

When an error occurs in a method the caller of the method is notified


by throwing an exception object, this object should be of the type
class Throwable.
Throwable has two subclasses, Error and Exception.

Object
Throwable
Error

Exception
RuntimeException

Copyright 2008 Pratian Technologies


www.pratian.com

Basic Java

Unit 6 Exception Handling

Errors

Errors are exceptional conditions that are external to the


application, and that the application cannot anticipate or recover
from, therefore Errors are not handled by the application.
For example,

An application has to open a file and write to it, due to some


hardware error, the application is unable to open the file we would
get a java.io.IOError.

Copyright 2008 Pratian Technologies


www.pratian.com

Basic Java

Unit 6 Exception Handling

Types of Exception

Object
Throwable
Error

Exception
RuntimeException

Copyright 2008 Pratian Technologies


www.pratian.com

Basic Java

Unit 6 Exception Handling

Types of Exception

Exceptions are of 2 types

Checked exceptions
Unchecked or runtime exception

Copyright 2008 Pratian Technologies


www.pratian.com

Basic Java

Unit 6 Exception Handling

Checked exceptions

Types of Exception

These are exceptional conditions that a well written application


should anticipate and recover from.
Since these exceptions are anticipated and are recoverable
conditions, compiler forces these exceptions to be handled.
e.g.: FileNotFoundException, IOException, SQLException

Unchecked or runtime exception

These are exceptional conditions that are internal to the


application, and that the application cannot anticipate or recover
from.
These usually indicate programming bugs, such as logical errors or
improper use of an API.
Since these can be fixed programmatically, compiler does not
force these exceptions to be handled.
e.g.: NullPointerException, ArrayIndexOutOfBoundsException

Copyright 2008 Pratian Technologies


www.pratian.com

Basic Java

Unit 6 Exception Handling

No need to import any java package


Java programming language supports, exception handling
by providing three exception handler components, these
are

How do I handle exceptions?

try
catch
finally

The try, catch and finally blocks are used to write an


exception handler.

Copyright 2008 Pratian Technologies


www.pratian.com

Basic Java

Unit 6 Exception Handling

try Block

Any code that might throw an exception is enclosed


within a try block. It is the first step in constructing an
exception handler.
try
{
code
..

try block

Copyright 2008 Pratian Technologies


www.pratian.com

Basic Java

Unit 6 Exception Handling

try Block Example

public int countChars(String fileName)


{
int total = 0;
try {
FileReader r = new FileReader(fileName);
while( r.ready()) {
r.read();
total++;
}
r.close();
}
}

Copyright 2008 Pratian Technologies


www.pratian.com

Basic Java

Unit 6 Exception Handling

catch Block

The catch block contains


code that is executed if and
when the exception occurs.
A catch block is an exception
handler associated with a try
block and handles the type of
exception indicated by its
argument.

try
{
}
catch(ExceptionType name)
{
}
catch(ExceptionType name)

Every try block is associated


with zero or more catch
block

Copyright 2008 Pratian Technologies


www.pratian.com

Basic Java

{
}

Unit 6 Exception Handling

catch Block Example

public int countChars(String fileName)


{
int total = 0;
try {
FileReader r = new FileReader(fileName);
while( r.ready()) {
r.read();
total++;
}
r.close();
}
catch(FileNotFoundException e){
System.out.println("File named " + fileName + "not found. " +e);
total = -1;
}
catch(IOException e){
System.out.println(Unable to perform I/O, please try later);
total = -1;
}
}
Copyright 2008 Pratian Technologies
www.pratian.com

Basic Java

Unit 6 Exception Handling

Try Catch Block Example

public static double divide(int a, int b)


{
double quotient=0;
try{
quotient=a/b;
} catch (ArithmeticException e)
{ System.out.println(" Divisor is zero");}
return quotient;
}

Copyright 2008 Pratian Technologies


www.pratian.com

Basic Java

Unit 6 Exception Handling

Try catch Block Example

public static void main(String[] args)


{
int a=0;
int b=0;
try{
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
}
catch (NumberFormatException e)
{
System.out.println(" Please enter an integer only ...");
}
double ans=divide(a,b);
System.out.println("The quotient is "+ ans);
}

See listing : HandledDivisionErroDemo.java

Copyright 2008 Pratian Technologies


www.pratian.com

Basic Java

Unit 6 Exception Handling

Exercise

Write some code that is capable of generating exceptions


like
ArithmeticException,
NumberFormatException,
ArrayIndexOutOfBoundsException etc
Write an exception handler, that is, enclose these line of
code in try block and write appropriate catch blocks to catch
different exception types.

Copyright 2008 Pratian Technologies


www.pratian.com

Basic Java

Unit 6 Exception Handling

Exception Handler

It is possible to write a generic catch block to catch any


type of exception that might occur

public int countChars(String fileName) {


int total = 0;
try {
FileReader r = new FileReader(fileName);
while( int c = r.read() != -1)
total++;
r.close();
}
Such
Whenever
an catch
catch(FileNotFoundException
e){a generic
block
Exception
should
than
System.out.println("File named
" other
+ be
fileName
+ "not found. " +e);
included
FileNotFound
at theorend,
}
after
IOException
the specific
occur,
catch(IOException e){
catch
this catch
blocks
block is
System.out.println(Unableinvoked
to perform I/O, please try later);
}
catch(Exception e){
System.out.println(Unable to continue processing, due to
some
internal error);
}
Copyright 2008 Pratian Technologies
Basic Java
www.pratian.com
}

Unit 6 Exception Handling

Clean up code

public int countChars(String fileName)


{
int total = 0;
Developer needs to
try {
perform clean up
FileReader r = new FileReader(fileName);that is, release the
file that was opened
while( r.ready()) {
programmatically
r.read();
total++;
}
r.close();
}
catch(FileNotFoundException e){
System.out.println("File named " + fileName + "not found. " +e);
total = -1;
r.close();
}
catch(IOException e){
System.out.println(Unable to perform I/O, please try later);
total = -1;
r.close();
}
Copyright 2008 Pratian Technologies
www.pratian.com

Basic Java

Unit 6 Exception Handling

finally Block

A finally block is executed irrespective of whether the try block


throws an error or not.
finally block is guaranteed to be executed and can be used for any
clean-up code.
If no catch block matches an exception thrown, control is transferred
to the finally block.
There can be only one finally block for a try block.
try{
}
catch(ExceptionType name){
}

finally{
}

Copyright 2008 Pratian Technologies


www.pratian.com

Basic Java

Unit 6 Exception Handling

finally Block Example

public int countChars(String fileName) {


int total = 0;
FileReader r = new FileReader(fileName);
try {
while( r.ready()) {
r.read();
total++;
}
}
catch(FileNotFoundException e){
System.out.println("File named " + fileName + "not
found. " + e);
total = -1;
}
catch(IOException e){ Clean up code
System.out.println("IOException
goes into finallyoccured "+ "while
counting " + e);
block
total = -1;
}

finally {
r.close();
}

Copyright 2008 Pratian Technologies


www.pratian.com

Basic Java

Unit 6 Exception Handling

Copyright 2008 Pratian Technologies


www.pratian.com

System-Defined Exception

Basic Java

Unit 6 Exception Handling

IndexOutOfBoundsException :

When refer to object as a null pointer

SecurityException :

When using a negative size of array

NullPointerException :

When assign object of incorrect type to element of array

NegativeArraySizeException :

When beyond the bound of index in the object which use index, such
as array, string, and vector

ArrayStoreException :

System-Defined Exception

When violate security. Caused by security manager

IllegalMonitorStateException :

When the thread which is not owner of monitor involves wait or notify
method

Copyright 2008 Pratian Technologies


www.pratian.com

Basic Java

Unit 6 Exception Handling

Throwing an Exception

All methods use the throw statement to throw an exception.


The throw statement requires a throwable object as argument. A
throwable object are instances of any subclass of the Throwable
class.
throw causes the method to terminate and returns an exception
object to the caller.
public static double divide(int a, int b)
{double quotient=0;
try{ if (b==0)
{ throw new ArithmeticException();
}
quotient=a/b;
}
catch (ArithmeticException e)
{ System.out.println(e.getMessage()+"\n Divisor is zero");
}
return quotient;
}

See listing : ThrowDivisionErroDemo.java


.

Copyright 2008 Pratian Technologies


www.pratian.com

Basic Java

Unit 6 Exception Handling

Propagation of uncaught exception.

Copyright 2008 Pratian Technologies


www.pratian.com

Basic Java

Unit 6 Exception Handling

The throws clause

A method can specify to throw an exception by


adding a throws clause to the method declaration.

The throws clause comprises the throws keyword


followed by a comma-separated list of all the
exceptions thrown by that method.

The clause goes after the method name and


argument list and before the brace that defines the
scope of the method.

public void writeList() throws FileNotFoundException,


IOException {

}
Copyright 2008 Pratian Technologies
www.pratian.com

Basic Java

Unit 6 Exception Handling

Propagation of uncaught exception.

public class PropagatingExceptionTest {


void method1() throws IOException
{ ..

method2();

void method2() throws IOException


{

throw new IOException();

.
}

public static void main(String[]


Basic Javaargs) throws IOException {

Copyright 2008 Pratian Technologies


www.pratian.com

Unit 6 Exception Handling

Exception handling mechanism


GUI

Control

userLoginForm()
{
authenticateUserInControl();
}
Handles
Exception with
authenticateUserInControl()
try/catch
{
authenticateUser();

Business Logic

Database

}
authenticateUser() throws Exception
{
Throws
retrieveUserInfo()
exception
}
retrieveUserInfo() throws Exception
{
retrievesData()
{
}
}

See listing : ThrowsDemo.java


Copyright 2008 Pratian Technologies
www.pratian.com

Basic Java

Unit 6 Exception Handling

Some Useful Methods

The Throwable class has some useful methods that can


be called on any Exception type

String getMessage()

Returns the message that was set while the exception object was
created, by calling the parameterized constructor

Exception(String message)

String toString

Returns a String representation of the exception object

void printStackTrace()

Copyright 2008 Pratian Technologies


www.pratian.com

Basic Java

Unit 6 Exception Handling

StackTrace

printStackTrace() method helps to trace the origin of the


Exception

Copyright 2008 Pratian Technologies


www.pratian.com

Basic Java

Unit 6 Exception Handling

User defined Exceptions

If an exception cannot be
represented by those in
the Java platform, a user
can define his own
exception.
The user defined
exception class should
be
a
subclass
of
Exception or any of its
sub types.

public class
ProductNotFoundException
extends Exception
{
}
public Product getProduct(int
prodId) throws
ProductNotFoundException {

Copyright 2008 Pratian Technologies


www.pratian.com

Basic Java

Unit 6 Exception Handling

Throwing Exceptions

Use the throw clause to throw the user defined exception object
The throw statement requires a throwable object as argument.
Throwable objects are instances of any subclass of the Throwable
class.
throw causes the method to terminate and returns an exception
object to the caller.
public Product getProduct(int prodId) throws
ProductNotFoundException {
// Retrieve product info from the database
// select * from Product where prod_id = prodId
if(!found)

throw new
ProductNotFoundException();
return product;
}

Copyright 2008 Pratian Technologies


www.pratian.com

Basic Java

Unit 6 Exception Handling

User defined Exceptions


Exception

AgeException

OutOfAgeLimitException

TooYoungException

IllegalAgeFormatException

TooOldException

NegativeAgeException

See listing : UserDefinedExceptionsDemo.java


Copyright 2008 Pratian Technologies
www.pratian.com

Basic Java

Unit 6 Exception Handling

Question time

Please try to limit the questions to the topics discussed during the session. Thank you.

Copyright 2008 Pratian Technologies


www.pratian.com

Basic Java

Вам также может понравиться