ExceptionHandling1

Download Report

Transcript ExceptionHandling1

Exception Handling
Contents
1.
Many classes in the Java standard library throw exceptions
2.
“throws clause” (or try-catch block) is needed in the function header
of any function that contains a message to a library method that
throws an exception
3.
Error message if “throws clause” or try-catch blocks are missing
4.
Types of exceptions
5.
Try-catch blocks
6.
The Exception hierarchy
7.
An example using try-catch blocks
8.
The anatomy of an exception
Exception Handling
Most of Java’s I/O classes (and many others) throw exceptions.
For example: Consider a function with a message readLine( ) directed to a
BufferedInputReader object
import java.io.*;
//needed for streams and IOException
public class ExceptionalExample {
public static void main(String [ ] args) throws IOException
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
System.out.println(“Enter a number”);
String str = br.readLine( );
The statement
“throwstoIOException”
is required
when
using
Provide
stream
readers
characters
as integers)
Read the
supplied
numberconvert
(as a String)
from (read
the keyboard.
readLine(
It must
be included
header of any function in
into
a string,).then
prompt
the userin
forthe
a number.
which readLine( ) appears.
Exception Handling
If we fail to include the “throws IOException” clause in the main
function header we will see the following error reported when we compile
the program ExceptionalExample:
c:\javacode>javac ExceptionalExample.java
ExceptionalExample.java:10: unreported exception java.io.IOException; must be
caught or declared to be thrown
String str = readLine( );
^
1 error
c:\javacode>
Method readLine( ) throws an IOException. Any function that uses it
must either throw the same exception (and pass the buck to the
operating system to handle the exception) or catch the exception and
provide its own error handling methodology. In the previous example
we chose the first strategy.
Exception Handling
Types of exceptions
Checked exceptions – inability to acquire system resources (such as
insufficient memory, file does not exist)
Java checks at compile time that some mechanism is explicitly in place to
receive and process an exception object that may be created during runtime
due to one of these exceptions occurring.
Unchecked exceptions – exceptions that occur because of the
user entering bad data, or failing to enter data at all.
Unchecked exceptions can be avoided by writing more robust code that
protects against bad input values. Java does not check at compile time to
ensure that there is a mechanism in place to handle such errors.
It is often preferred to use Java’s exception handling capabilities to handle bad
user input rather than trying to avoid such circumstances by providing user-input
validation in the code.
Exception Handling
The try / catch blocks
try {
//statements – one of which is capable of throwing an exception
}
catch (ExceptionTypeName objName) {
//one or more statements to execute if this exception occurs
}
finally {
//statements to be executed whether or not exception occurs
}
Encapsulate statement or statements that can throw an exception in
One
or
moreblock
catch
blocks
immediately
follow
aoftry
block
a try
Each
An
block.
optional
catch
finally
specifies
blockmust
the
cantype
be
added
of exception
at the
end
that
itthe
handles
catchto
in
provide
error
handling
for anythat
exceptions
thatexecuted
occur
a blocks
parameter
to provide
list.
a setroutines
of statements
are always
while
executing
in the try block.
whether
or notthe
anstatements
exception occurs.
Exception Handling
The exception hierarchy (partial)
Exception
DataFormatException
IOException
NumberFormatException
EOFException
FileNotFoundException
RunTimeException
InterruptedIOException
All
Common
exceptions
Exception
sub
fromclasses
a base
include:
class Exception
IOException
caninherit
be decomposed
specific
classes
of I/O errors
NumberFormatException
is into
a subclass
of
DataFormatException
Exception Handling
Example
Consider implementing the BufferReader readLine( ) example with
try-catch clocks.
import java.io.*
public class ExceptionalExample {
public static void main(String [ ] args) //no throws clause used here
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
System.out.println(“Enter a number”);
try {
String str = br.readLine( );
double num = Double.parseDouble(str);
}
Will throw NumberFormatException if str
cannot be converted to a double.
try block encapsulates
the readLine( ) method
and the conversion from
String to double.
Exception Handling
Example (continued)
//add the catch blocks
catch (IOException ioe) {
//print a message to the screen
System.out.println(ioe.toString( ));
}
catch (Exception e) {
catch the IOException object
thrown by readLine( )
Note! ioe is a handle
(reference) to an IOException
object thrown by readLine( )
//catch any other exception and print a message to the screen
System.out.println(e.toString( ));
}
finally {
System.exit(0);
}
Note! toString( ) is a method that all
Classes inherit (implicitly).
In the finally clause we ensure that the
program
terminates
properly
– exit(0)
signifies
Since both
catch blocks
have
the same
normal
termination.in this example, there is no need
implementation
to single out IOException in a separate block.
Exception Handling
The anatomy of an exception
ExceptionalExample
try {
String str =br.readLine( );
}
catch (IOException ioe){
System.out.println(ioe.toString());
}
In the main( ) function of
An
br.readLine(
error occurs
) iswhile
called
inside of
ExceptionalExample
a attempting
The IOException is passed
to the
to
a
read
try
block
from
in
the
function
keyboard.
main(
An) is
Message
is
sent
to
object
BufferedReader
object called
catch block in function
main(br
)
IOException
object
created.
referenced
by
ioe toisto
execute
created
and attatcher
isr. its
toString( ) method (inherited from
implicit base class Object)
IOException
br:BufferedReader
new
readLine( ) {..}
toString( ) {…}