|
Exceptions
An Introduction with Examples in Java |
|
Prof. David Bernstein
|
| Computer Science Department |
| bernstdh@jmu.edu |
String
into a double?
double values are legitimate return values
there is no special value that can be used.
return statement (with or without a value
to return)throw statement
(which must pass back a Throwable object)Throwable should
be used)
void)throws
clause (that specifies the exception)
In the following example, a throw statement is used
for an alternative return and the return statement
is used for a normal return.
try block is used to indicate the code that
should be executed when the method returns normallycatch block (which is passed a
Throwable) is used to indicate the code that
should be executed when the method returns "abnormally"try-catch Statement (cont.)
catch Portion
catch(NumberFormatException nfe) { total += DEFAULT; }
NumberFormatException object that this statement
is going to "catch" and name nfe.
try-catch
throws clause in the declaration)
Catch Blocks
catch Block:
catch blocks (but it is better to
use a logger)main()?
catch blocks that are in
the main() method
Beginning programmers often make the following mistake
when told that a method must throw an exception. For example, if
they are told that the method they are writing must throw a
NumberFormatException they add a throws
NumberFormatException clause to the method declaration and do
the following.
Instead you should add a throws NumberFormatException
clause to the method declaration and do the following.
The only reason to include a throw statement in
a catch block is if a different exception must be
thrown.
The following two fragments have very different behavior.
javaexamples/exceptions/NestedBlockExample.java (Fragment: 0)
try-catch Blocks
parseInt
generated the exception in the previous
example?try-catch statements
ArrayIndexOutOfBoundsException so I'll fix it by
adding a try-catch block.")
throws clause in its declaration
{exceptions=name[,...]}
after the return type of the method to indicate that
exceptions are thrown