Sei sulla pagina 1di 22

11

Handling Exceptions:
An Overview
Objectives
After
After completing
completing this
this lesson,
lesson, you
you should
should
be
be able
able to
to do
do the
the following:
following:
•• Explain
Explain exception
exception handling
handling concepts
concepts
•• Explain
Explain the
the difference
difference between
between run
run time
time
exceptions
exceptions and
and checked
checked exceptions
exceptions
•• List
List the
the most
most common
common Java
Java exceptions
exceptions
•• Catch
Catch various
various types
types of
of exceptions
exceptions
•• Use
Use the finally keyword
the finally keyword

11-2
Overview
Traditional
Traditional error-handling
error-handling techniques:
techniques:
void highLevelMethod() {
if (!method1())
// Error recovery…
boolean method1() {
if (!method2()) boolean method2() {
return false; if (…problem…)
return false;

Exception
Exception handling
handling is
is cleaner:
cleaner:
•• Throw
Throw an
an exception
exception if
if an
an error
error occurs
occurs
•• Catch
Catch exception
exception in
in aa high-level
high-level method
method
11-3
What Is an Exception?

•• Java
Java methods
methods “throw
“throw anan exception”
exception” if
if
they
they fail
fail for
for some
some reason
reason
–– Control
Control returns
returns immediately
immediately to
to the
the
appropriate
appropriate “exception
“exception handler”
handler”
•• Exceptions
Exceptions are are aa more
more robust
robust and
and
cleaner
cleaner technique
technique forfor dealing
dealing with
with
errors
errors

11-4
Catching Exceptions

If
If you
you call
call aa method
method that
that might
might throw
throw an
an
exception:
exception:

Enclose
Enclose call
call try {
in try block
in try block // Might throw I/O exception
b = stream1.read();
b = stream2.read();
b = stream3.read();
}
Define
Define catch
catch catch ( IOException e ) {
block
block to
to deal
deal // Handle the exception
with
with exception
exception }

11-5
Throwable Classes
All
All errors
errors and
and exceptions
exceptions extend
extend the
the
Throwable class
Throwable class
Throwable

Error Exception

Abnormal Checked
unrecoverable exceptions RuntimeException
errors
Run time
exceptions
11-6
Examples
•• Errors:
Errors:
–– OutOfMemoryError,
OutOfMemoryError,
InternalError
InternalError
•• Checked
Checked exceptions:
exceptions:
–– MalformedURLException,
MalformedURLException,
IOException
IOException
•• Run
Run time
time exceptions:
exceptions:
–– ArrayIndexOutOfBoundsException,
ArrayIndexOutOfBoundsException,
ArithmeticException
ArithmeticException
11-7
Dealing with Multiple Exceptions

Use
Use multiple catch blocks
multiple catch blocks to
to deal
deal with
with
multiple
multiple types
types of
of exception
exception
try {
URL u = new URL("http://www.oracle.com");
URLConnection c = u.openConnection();
}
catch (MalformedURLException e) {
System.err.println("Could not open URL: " + e);
}
catch (IOException e) {
System.err.println("Could not connect: " + e);
}

11-8
The finally Keyword

•• A
A finally
finally clause
clause can
can be
be used
used to
to ensure
ensure
that
that aa block
block of
of code
code is
is always
always executed
executed
try {

}
•• Can
Can be
be used
used catch(AnException e) {
with
with or
or without
without …
aa catch
catch block
block }
finally {
// Always executed…
}

11-9
More About finally

The finally clause


The finally clause is
is executed
executed
regardless
regardless of of how
how the try block
the try block exits
exits
•• Normal
Normal termination,
termination, byby falling
falling through
through
the
the end
end brace
brace
•• Because
Because an exception was
an exception was thrown
thrown

11-10
Guided Practice:
try, catch, and finally
void makeConnection(String host) {
try {
URL u = new URL("http://" + host);
}
catch (MalformedURLException e) {
System.out.println("Cannot contact " + host);
return;
}
finally {
System.out.println("Don't forget about me");
}
System.out.println("Goodbye");
}
11-11
Declared Exceptions

•• Methods
Methods advertise
advertise which
which exceptions
exceptions
they throw, or
they throw, or do
do not
not catch:
catch:
public class URL {
public URL(String s) throws MalformedURLException
{ … }

•• You
You must catch these
must catch these declared
declared
exceptions
exceptions somewhere
somewhere in
in your
your code
code

11-12
Catching Declared Exceptions
Locally
One
One approach
approach is is to catch any
to catch any exceptions
exceptions
locally,
locally, in
in your
your method
method
public URL changeURL(URL oldURL) {
try {
return new URL("http://www.oracle.com");
}
catch (MalformedURLException e) {
return oldURL;
}
}

11-13
Passing Declared Exceptions
on to the Calling Method
Another
Another approach
approach is is to
to ignore
ignore the
the
exception
exception atat this
this level
level
•• Exception
Exception propagates
propagates to to calling
calling method
method
•• Must
Must advertise
advertise this
this fact
fact using
using throws
throws
public URL changeURL(URL oldURL)
throws MalformedURLException {
return new URL("http://www.oracle.com");
}

11-14
Throwing Exceptions
Throw
Throw exceptions
exceptions using
using the
the throw
throw
keyword
keyword
public void method1() {
try {
method2();
}
catch (IOException e) {
System.err.println("Caught: " + e);
}
public void method2() throws IOException {
}
if (…problem…)
throw new IOException();
}

11-15
You can create your own exception

class
class MyException
MyException extends
extends Exception
Exception
class
class TestEx
TestEx throws
throws MyException
MyException {{
void
void doStuff()
doStuff() {{
throw
throw new
new MyException();
MyException();
}}
}}

11-16
Assertions

Overview
Overview

11-17
Assertion expression rules
void
void noReturn()
noReturn() {{ }}
int
int aReturn()
aReturn() {{ return
return 1; 1; }}
void
void go()go() {{
int
int xx == 1;
1;
boolean
boolean bb == true;
true;
//// the
the following
following six six are are legal
legal assert
assert statements
statements
assert(x
assert(x == == 1);
1);
assert(b);
assert(b);
assert
assert true;
true;
assert(x
assert(x == == 1)
1) :: x;
x;
assert(x
assert(x == == 1)
1) :: aReturn();
aReturn();
assert(x
assert(x == == 1)
1) :: new
new ValidAssert();
ValidAssert();
//// the
the following
following six six are are ILLEGAL
ILLEGAL assert
assert statements
statements
assert(x
assert(x == 1);1); //// none
none of of these
these are
are booleans
booleans
assert(x);
assert(x);
assert
assert 0; 0;
assert(x
assert(x == == 1)
1) :: ;; //// none
none of of these
these return
return aa value
value
assert(x
assert(x == == 1)
1) :: noReturn();
noReturn();
11-18 assert(x
assert(x == == 1)
1) :: ValidAssert
ValidAssert va; va;
}}
Enabling assertions
••Identifier
Identifier vs
vs keyword
keyword
••Use
Use version
version 55 of
of java
java and
and javac
javac
••Compiling
Compiling assertion-aware
assertion-aware code
code

11-19
Enabling assertions (Contd.)

Running
Running with
with assertions
assertions
Enabling
Enabling assertions
assertions at
at runtime
runtime
Disabling
Disabling assertions
assertions at
at runtime
runtime
Selective
Selective enabling
enabling and
and disabling
disabling

11-20
Assertions usage rules

Don't
Don't use
use assertions
assertions to to validate
validate
arguments
arguments to to aa public
public method
method
Do
Do use
use assertions
assertions toto validate
validate arguments
arguments
to
to aa private
private method
method
Don't
Don't use
use assertions
assertions to to validate
validate
command-line
command-line arguments
arguments
Do
Do use
use assertions,
assertions, even
even in
in public
public
methods,
methods, to to check
check for
for cases
cases that
that you
you
know
know areare never,
never, ever
ever supposed
supposed to to happen
happen
Don't
Don't use
use assert
assert expressions
expressions that
that can
can
cause
cause side
11-21
side effects!
effects!
THANK YOU

For
For queries
queries
mridul.goel@hcl.in
mridul.goel@hcl.in

11-22

Potrebbero piacerti anche