Presentation on Handling Exceptions

Download Report

Transcript Presentation on Handling Exceptions

2. Program Construction
in Java
1
2.10 Errors and Exceptions
Types of error
• Programmers usually consider 3
‣
‣
‣
syntax,
logic/semantic,
run-time.
3
types:
Syntax errors
• Your program tries to break the rules of Java
and will not compile:
‣
‣
get to know the rules better,
consider carefully the messages that the
compiler returns.
4
Logic errors
• Your syntax is good but the way you have
constructed your algorithm is not:
‣
‣
‣
work through your algorithm carefully again
on paper (a trace table),
insert temporary test print out lines for the
values of problem variables at key points,
/*comment out certain portions*/ to se what
that does.
5
Runtime errors
• Hard to foresee special circumstances, if the
user puts in unexpected data or unusual
calculations occur e.g. division by zero:
‣
‣
‣
test programs thoroughly with valid/normal,
extreme and totally abnormal input,
try to anticipate what the user could do and
don't allow the unacceptable,
use Java's exception handling.
6
Run time errors
• At dat entry:
‣
‣
if you request input, anticipate alternatives
e.g. allow C or c,
use else to say “Sorry, don't recognise
input” and while loops to force another
input until they get it right.
7
Exceptions
• An exception is an error event in a Java
application.
• News that an exception has occured is
broadcast to allow it to be handled.
‣
when you write code that might cause an
error, put it in a try .. catch block, e.g.
when asking for an integer to be input...
8
Exceptions
‣
try {
int temperature = IBIO.input
("Please enter an integer");
}
catch (NumberFormatException e){
IBIO.output ("Not a valid
temperature: "+ e.getMessage));
}
9
Exceptions
• If the user inputs a value that cannot be
converted to an integer, a
NumberFormatException is thrown,
(which here we shall call e)
• e gets caught and handled by the statements
in the catch block.
• All exceptions have a getMessage()
method which can be used to reveal the
associated error message.
10
Types of exception
• ArithmeticException = arithmetic
error
e.g. division by zero.
• ArrayIndexOutOfBoundsException = an
array index is bigger or smaller than the
declared size of the array.
11
Types of exception
• ArrayStoreException
= assignment of
the wrong type of data into an array.
• IllegalArgumentException
= wrong
sort of argument passed to a method.
12
Exceptions
• It is possible to write your own Exception
classes, but this is not required for IB.
• Research other examples of exceptions...
13