Java Exception Handling Presentation

Document technical information

Format ppt
Size 586.2 kB
First found May 22, 2018

Document content analysis

Category Also themed
Language
English
Type
not defined
Concepts
no text concepts found

Persons

Organizations

Places

Transcript

1
SSD3 Unit 1
Java Exception
Handling
Presentation #1
Website: http://www.icarnegie.com
2
Review 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
Java Programming Tools
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

4
Can 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.
5
Java 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
Object
Throwable
Error
Exceptions
. . .
RuntimeException
UserException
. . .
ArithmeticException
IndexOutOfBoundsException
NullPointerException
7
• Example of ArithmeticException
•
•
int j = 0;
j = 1 /j;
Exception occurred during event dispatching:
java.lang.ArithmeticException: / by zero
at Greeting.paint(Greeting.java:5)
at sun.awt.RepaintArea.paint(Unknown Source)
• Example of IndexOutOfBoundsException
•
•
int[] k = new int[10];
k[10] = 0; Exception occurred during event dispatching:
java.lang.ArrayIndexOutOfBoundsException
at Greeting.paint(Greeting.java:6)
at sun.awt.RepaintArea.paint(Unknown Source)
• Example of NullPointerException
•
•
Ball b1 = null; Exception occurred during event dispatching:
java.lang.NullPointerException
b1.move();
at Greeting.paint(Greeting.java:7)
at sun.awt.RepaintArea.paint(Unknown Source)
8
• The try-catch-final statement for exception handling
try {
statements
//possibly generate exceptions
}
catch (<exception> e) {
statements
//Exception handling code
}
.
.
.
//Other catch segments
finally {
statements
}
//Optional, always executed
9
Execution 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-catchfinally.
10
int[] a = null;
int n = 0;
//a = null;
//n = 1;
//a = new int[10];
//n = 10;
//a = new int[10];
//n = 9;
System.out.println("0: n = " + n);
0: n = 0
try {
4: Bye-bye
0: Run through
}
1: java.lang.ArithmeticException: / by zero
a[n] = 100 / n;
System.out.println( "0: a[" + n + "] = " + a[n]);
catch (ArithmeticException e1) {
System.out.println( "1: " + e1);
}
catch (NullPointerException e2) {
System.out.println("2: " + e2);
}
0:
2:
4:
0:
n=1
java.lang.NullPointerException:
Bye-bye
Run through
0: n = 10
3:java.lang.ArrayIndexOutOfBoundsExc
eption: 10
catch (IndexOutOfBoundsException e3) {
System.out.println("3: " + e3);
}
4: Bye-bye
0: Run through
finally {
0:
0:
4:
0:
}
System.out.println("4: Bye-bye");
System.out.println("0: Run through");
n=9
a[9] = 11
Bye-bye
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.
catch (RuntimeException e) {
System.out.println( e);
}
• A user may defines UserException subclasses, throws
objects of these new classes when certain conditions
occur during execution, and catches them.
12
Order 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.
13
Simple 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.
Object
InputStream
OutputStream
FileInputStream
FileOutputStream
read()
write()
close()
...
close()
...
outFile.dat
inFile.dat
Disk
15
16
17
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()
Closes the file.
//Throws IOException
• 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;
. . .
...File contents...
. . .
nByte = 755
r.available() = 755
System.out.print( (char) d);
DisplayFile
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); }
19
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 <crtl-d>.)
try {
FileOutputStream r = new FileOutputStream( “sam.dat”);
int nByte = 0;
int d = System.in.read();
while( d != 4) {
++nByte;
SaveFile
// 4 is the code for <crtl-d>
r.write( d);
C:\>java SaveFile
I love Hong Kong.
Bye-bye.
d = System.in.read();
}
r.close();
C:\>type sam.dat
I love Hong Kong.
Bye-bye.
}
catch ( IOException e) {
System.out.println("\n### IO Error: " + e);
}
22
Types 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 >= 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
24
Problem 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
25
Handling 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
26
Java 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
27
Handling 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
28
Code Example
Handling 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
29
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.
30
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.
31
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.
32
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.
33
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
34
Code Example:
IOException and FileNotFoundException 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();
}
}
}
35
Code Example:
FileNotFoundException using simpleIO
try{
SimpleReader in = new SimpleReader("PriceFile.txt");
for (int i = 0; i < 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());}
36
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
37
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.
38
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.
39
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( ) {…}
40
Moral 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.
41
Questions?

Similar documents

×

Report this document