Title: SSD3 Unit 1
1- SSD3 Unit 1
- Java Exception Handling
- Presentation 1
- Website http//www.icarnegie.com
2Review of Java
- Java is an object-oriented language
- Java is a relatively simple object-oriented
language, compared to others such as C - It borrows many features from other popular
programming languages such as C and C - It runs on many different types of machine
a.k.a Platform Independent - It has built in functionality and programs that
are accessible to all programs.
3- Software Development Kit (SDK)
- Java Software Development Toolkit
- Available from Sun Microsystems, Inc.
- SDK 1.4.2_04 is the latest professional version
- SDK 1.5.0 Beta is coming soon
- Known as JDK in early versions
- Interface Development Environments (IDE)
- IBM Others Eclipse (Open Source free!)
- Plug-ins Omondo for UML diagramming
- Sun - Forte
- Microsoft - Visual J
- Borland - JBuilder
- Oracle - JDeveloper
4Can Errors happen in my Java Program?
- Yes!
- The methods that you use in Java may not always
work under all circumstances, thus Exception
Handling is used to plan ahead for potential
errors by coding in exception statements into the
code. - What are Exceptions?
- Exceptions are a way for the Java Virtual Machine
(JVM) to signal that a serious error condition
has arisen during program execution, one that
could potentially cause your program to crash. - What about Exception Handling?
- Exception handling enables a programmer to
gracefully anticipate and handle such exceptions
by providing a way for a program to transfer
control from within the block of code where the
Exception arose known as the try block into a
special error handling code block known as the
catch block.
5Java Exceptions, File Input and Output
- Types of exceptions
- Error
- unrecoverable, not supposed to be handled by
users. - AWTError, LinkageError, ThreadDeath,
VirtualMachineError - RuntimeException
- ArithmeticException, IndexOutOfBoundsException,
NullPointerException, IOException. . . - UserException
6- The hierarchy of the relevant classes
7(No Transcript)
8- The try-catch-final statement for exception
handling
try statements //possibly generate
exceptions catch (ltexceptiongt e)
statements //Exception handling
code . . . //Other catch segments finally
//Optional, always executed statements
9Execution of the try-catch-final statement
- First execute the try block.
- If an exception occurs, the execution of the try
block is terminated. An object of the
corresponding class was thrown . - If the object is an error object, the execution
of the program is terminated. - If the object matches with one of the exceptions
specified in a catch segment, the catch block is
executed. - The finally block is optional. But if it exists,
it is always executed, even when there is no
exception occurs. - The execution moves to the statement after the
try-catch-finally.
10int a null //a null //a new
int10 //a new int10 int n 0
//n 1 //n 10 //n
9 System.out.println("0 n " n) try
an 100 / n System.out.println( "0
a" n " " an) catch
(ArithmeticException e1) System.out.println(
"1 " e1) catch (NullPointerException e2)
System.out.println("2 " e2) catch
(IndexOutOfBoundsException e3) System.out.print
ln("3 " e3) finally System.out.printl
n("4 Bye-bye") System.out.println("0 Run
through")
0 n 0 1 java.lang.ArithmeticException / by
zero 4 Bye-bye 0 Run through
0 n 1 2 java.lang.NullPointerException 4
Bye-bye 0 Run through
0 n 10 3java.lang.ArrayIndexOutOfBoundsExcepti
on 10 4 Bye-bye 0 Run through
0 n 9 0 a9 11 4 Bye-bye 0 Run through
11- In last example, if there is no need to handle
the exceptions individually, we can replace the
three catches with a single catch block. - A user may defines UserException subclasses,
throws objects of these new classes when certain
conditions occur during execution, and catches
them.
catch (RuntimeException e) System.out.println
( e)
12Order of catches
- If a method does not catch an exception, the
execution of the method will be cut short. The
exception object is then thrown out to the caller
of the method level by level upward. - v.main() catch
-
- a.f1() no catch
-
- x.f2() Exception occurs, no catch
- If a user does not catch an RuntimeException
object, Java exception handler will eventually
catch it and terminate the execution.
13Simple file input/output
- In physical world, a stream is a continuous flow
of water - In java, a byte stream is a sequence of bytes.
- An input stream is a source from which bytes are
read one by one. Eg, a keyboard, a disk file
opened for reading. - An output stream is a destination to which bytes
are written one by one. Eg, a monitor, a printer,
a disk file opened for writing.
14- A disk file for reading in a program is mapped to
an object of FileInputStream. - A disk file for writing in a program is mapped to
an object of FileOutputStream.
15(No Transcript)
16(No Transcript)
17(No Transcript)
18- FileInputStream( String fileName)
- Creates a FileInputStream object and maps it to
an actual disk file for reading //Throws
FileNotFoundException - int available() //Throws IOException
- Returns the number of bytes left in the file
that can be read. (Decrement by 1 after a byte is
read.) - int read() //Throws IOException
- Reads a byte of data from the file. Returns
-1 if the end of file is reached. - void close() //Throws IOException
- Closes the file.
19- A program that prints the contents of a file on
screen
try FileInputStream r new FileInputStream(
e.dat) int a r.available() int
nByte 0 int d r.read() while ( d
! -1) nByte System.out.print(
(char) d) d r.read() r.close()
System.out.println( "\nnByte " nByte)
System.out.println( "r.available() " a
) catch ( IOException e)
System.out.println("\n IO Error " e)
. . . ...File contents... . . . nByte
755 r.available() 755
DisplayFile
20- Class FileOutputStream
- FileOutputStream( String fileName)
- Creates an OutputFileStream object and maps it
to the disk file with the specified name for
writing. - Void write( int b)
- Writes the specified byte to the file.
- Void close( )
- The exceptions thrown are similar to that of
FileInputStream.
21- This program saves the characters typed on a
keyboard into a disk file. (The end is indicated
by typing a ltcrtl-dgt.)
try FileOutputStream r new FileOutputStream(
sam.dat) int nByte 0 int d
System.in.read() while( d ! 4) // 4 is
the code for ltcrtl-dgt nByte r.write(
d) d System.in.read() r.close() catc
h ( IOException e) System.out.println("\n
IO Error " e)
SaveFile
C\gtjava SaveFile I love Hong Kong. Bye-bye. C
\gttype sam.dat I love Hong Kong. Bye-bye.
22Types of Problems
- unexpected conditions
- error conditions
- examples
- write to disk no disk in A\, or disk full
- bad inputs from user in a TextField
- use an array item with index gt length
23"Trapping" Problems
- catch problems before they crash the program, and
then either - end the program with all normal clean up
- keep running around (not though) code related to
the error (limited functionality) - provide a message for user to fix problem e.g.,
put the diskette in the A\ drive
24Problem Types
- Java has a class called Throwable, two other
classes inherit from it - Error serious problem, not possible for program
to fix it - e.g., user can put a disk in A drive, but program
can't - Exception possible to adjust for problem within
the program - Two that are of interest to us are
- IOException
- FileNotFoundException
25Handling Fatal Errors
- try to terminate program "gracefully"
- save as much good data as can, then shut down
- provide an error message that tells where problem
occurred or what to do next
26Java Exception Handling
- based on a language design choice
- easy to use (built-in feature)
- handle problems with special code
- problem handling code doesn't get mixed up with
processing code - makes code more understandable, easier to maintain
27Handling Exceptions
- add 2 things to code
- try block keyword try followed by curly brackets
around code where error could occur - catch block (right after try block)
- catch(exception type instance name)
- statements to handle exception, surrounded by
curly brackets
28Code ExampleHandling Exceptions
- divideIt(int x, int y)
-
- try
- int result x/y
-
- catch(ArithmeticException err)
- System.out.println("Division by zero")
//1 - System.out.println(err.getMessage)
//2 - // 1 user-defined message
- // 2 object err gets system
message
29Exception Handling
Most of Javas 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(Syst
em.in) BufferedReader br new
BufferedReader(isr) System.out.println(Enter a
number)
String str br.readLine( )
The statement throws IOException is required
when using readLine( ). It must be included in
the header of any function in which readLine( )
appears.
Provide stream readers to convert characters
(read as integers) into a string, then prompt the
user for a number.
Read the supplied number (as a String) from the
keyboard.
30Exception 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\javacodegtjavac ExceptionalExample.java
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.
31Exception 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 Javas exception
handling capabilities to handle bad user input
rather than trying to avoid such circumstances by
providing user-input validation in the code.
32Exception 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 a try block.
One or more catch blocks must immediately follow
a try block to provide error handling routines
for any exceptions that occur while executing the
statements in the try block.
Each catch block specifies the type of exception
that it handles in a parameter list.
An optional finally block can be added at the end
of the catch blocks to provide a set of
statements that are always executed whether or
not an exception occurs.
33Exception Handling
The exception hierarchy (partial)
All exceptions inherit from a base class Exception
Common Exception sub classes include
IOException can be decomposed into specific
classes of I/O errors
NumberFormatException is a subclass of
DataFormatException
34Code ExampleIOException and FileNotFoundExceptio
n Required
- / Throws an IO exception because the
- file zxcvb.txt doesn't exist. /
- import java.io.
- public class IoError
-
- public static void main(String args)
-
- try FileReader f new FileReader("zxcvb.txt
") - catch(IOException e)
-
- e.printStackTrace()
-
-
-
35Code ExampleFileNotFoundException using simpleIO
try SimpleReader in new
SimpleReader("PriceFile.txt") for (int i 0
i lt length i) type
in.getString() // pizzaType price
in.getDouble() //price // don't forget to
close the file in.close() catch
(FileNotFoundException anException)
System.out.println("PriceFile.txt File Not Found
") catch (IOException anException)
System.out.println(anException.toString())
36Exception Handling
Contents
- Many classes in the Java standard library throw
exceptions - 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 - Error message if throws clause or try-catch
blocks are missing - Types of exceptions
- Try-catch blocks
- The Exception hierarchy
- An example using try-catch blocks
- The anatomy of an exception
37Exception 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(S
ystem.in) BufferedReader br new
BufferedReader(isr) System.out.println(Enter a
number) try String str br.readLine(
) double num Double.parseDouble(str)
try block encapsulates the readLine( ) method and
the conversion from String to double.
38Exception 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 any other exception
and print a message to the screen
System.out.println(e.toString( )) finally
System.exit(0)
Note! ioe is a handle (reference) to an
IOException object thrown by readLine( )
Note! toString( ) is a method that all Classes
inherit (implicitly).
In the finally clause we ensure that the program
terminates properly exit(0) signifies normal
termination.
Since both catch blocks have the same
implementation in this example, there is no need
to single out IOException in a separate block.
39Exception Handling
The anatomy of an exception
In the main( ) function of ExceptionalExample a
BufferedReader object called br is created and
attatcher to isr.
br.readLine( ) is called inside of a try block in
function main( )
An error occurs while attempting to read from the
keyboard. An IOException object is created.
The IOException is passed to the catch block in
function main( )
Message is sent to object referenced by ioe to
execute its toString( ) method (inherited from
implicit base class Object)
try String str br.readLine( )
catch (IOException ioe) System.out.println(
ioe.toString())
new
readLine( ) ..
toString( )
40Moral of the Story
- Think First!
- Plan ahead with your coding and identify what
methods and packages you will need in order to
create the functionality you want in Java. - Think Quick!
- Use the Java API and other documentation to
quickly verify errors that may be thrown. - Think Smart!
- Try to write error messages that will be clear
and easily understood by the users of your
system. Also ALWAYS document your code with Java
comments for future reference.
41Questions?