Lecture 4 - Exceptions
Motivation:
when it’s not possible for a method to “do its job”
e.g.,
call L.remove(-1) with invalid position
or call it.next() when it.hasNext() is false
can be caused by
logical
error in a method’s code –- debug/remove error
logical
error in a client’s code
bad
file input data
Alternative ways of handling client
code & input file errors
in some cases, could do nothing, but
error
is not detected…
sometimes can’t do nothing (e.g., need to
return a value)
in
some cases, could return a special
error value –
might not be possible (e.g., returns int)
might be ignored
makes code clumsy
could
print an error message (and quit)
but calling code (client) can usually print
a more
meaningful message –
e.g., knows name of List
and quitting doesn’t give the client a chance to
handle the error gracefully
e.g., close files, print
meaningful message, etc.
instead: throw an exception,
throw
new ex-type(); //note "new" and
"()"
· exception is handled by
client code
· the code that throws the
exception
o
does
not catch the exception
o
usually
does not print an error message
public
void add(int pos, Object ob){
if
(pos < 1 || pos > numItems)
throw new IndexOutOfBoundsException();
…
not:
try
{
if (pos < 1 || pos > numItems)
throw new IndexOutOfBoundsException();
…
}
catch (IndexOutOfBounds ex) {
System.out.println("bad position in
List");
}
add method in
List doesn’t know the name of "this" List,
doesn't print error message or catch the
exception,
just throws the exception
Announcements
· Homework #1 due today
(hand in text file)
· Programming
assignment 1
due Tuesday
· Homework 2 is posted, due next Thurs
– lists, complexity
· Java review
session today,
Topics:
arrays, nexted loops, file i/o, Unix commands
· Print &
read for Tuesday: notes on program complexity analysis
· General approach to
reading:
Read on-line notes before class
Review lecture notes & on-line notes
after class
Read relevant chapter of text for further
background
e.g.
chapter 9 for program efficiency analysis,
chapter 7 on “iterators” for iterators,
etc.
client code: catch exceptions
using a try block:
try {
inFile = new File(filename);
br = new BufferedReader(new FileReader(inFile));
String word = br.readLine();
code to
get pos from word;
L.get(pos)…
}
catch(IOException ex) {
System.out.println("Error trying to read from file "
+ args[0]);
Sytstem.out.print("Enter new file name:
");
…
} catch
(IndexOutOfBoundException ex2) {
code
to handle Index out of bounds exception
}
finally { // optional – usually leave out
statements
that always execute before leaving this try block
}
· other
exceptions are propagated up the call chain…
if
not caught, the program will stop with an error message
three choices:
· catch and handle the
exception
· can throw the exception
again after handling it
· ignore the exception (let
it propagate up the call chain)
"checked"/"unchecked"
exceptions
o
specified
in Java documentation for exception type
o
IndexOutOfBounds
is unchecked;
o
IOException,
FileNotFound are checked
o
need
a “throws” clause in the header of a method only if the method might
throw a checked exception
private
m3() throws IOException { … }
o
code
that calls a method that might throw a checked exception, must either
§
be
in a try/catch block, or
§ must have a throws clause
in the header of the method that contains the calling code
example:
void m1() {
void m2() { void m3() {
m2(); m3(); A[-1] = 0;
... … ...
} } }
·
statement with bad index is not in a try
·
exception is passed up to m2; also not in a
try
·
exception is passed up again, etc.
What if we replace A[-1] = 0; with call to
readLine()?
· can
throw a checked IOException
· put
call to readLine in a try/catch block
· m3()
throws IOException, same choices for m2(), etc
What exception to throw?
· Use an existing exception
–
e.g.,
IndexOutOfBoundsException, IOException, etc.
· Or define and throw your
own exception
Java exceptions are objects (instances of
classes), created by using new,
e.g., in the List get
method if passed a bad position:
throw new
IndexOutOfBoundsException();
or
throw new
IndexOutOfBoundsException(s);
// s is a
String that contains an error message
How to define/throw your own
exceptions:
· Define an exception by
defining a public class:
public
class myException extends RuntimeException {
} // often leave the
exception class empty
· all user defined
exceptions must be sub-classes of Throwable;
· sub-classes of Exception
are checked;
· subclasses of RuntimeException are unchecked
·
You
can optionally include fields, methods
e.g.,
a String field to contain an error message
· Once defined, you can
throw the exception using a throw statement
throw
new MyException();
Summary:
· If a method can’t do it’s
job, it should throw an exception
throw
new XXXException();
· Can use “built-in”
exceptions, or define new ones using a new class that extends Exception
(checked) or RuntimeException (not checked)
· Client code should catch
exceptions using try/catch
· If a method has a
statement that might throw a checked exception,
o
it
must be called in a try/catch,
o
or
the header of the calling method must have a
“throws clause”
Note:
throws clause in header is part of method's signature;
if
the method specification doesn't have throws clause,
need
to use try/catch instead
Exercise in class: