3. Error and Error Handling.
v
An Error is any unexpected result obtained from a program during execution.
v
Unhandled errors may manifest themselves as incorrect
results or behavior, or as abnormal program termination.
v
Errors should be handled by the programmer, to prevent
them from reaching the user.
4. Exception
Exception- a better error handling.
Exception – an error condition that can occur during the
course of a program
execution
Ø
In Java, exceptions are objects themselves
Exception handling is another form of control structure
(like ifs and switch statements)
Ø
When an error is encountered, the normal flow
of the program is stopped and the exception is
Handled.
7. Try…catch block
•
To process an exception when it occurs, the line that throws the exception is
executed within a try block.
• A try block is followed by one or more catch clauses, which
contain code to process an exception.
•
The catch statement is used for catching exceptions.
try
{
<try block>
}
catch ( <ExceptionClass> <name> )
{
<catch block>
}
catch ( <ExceptionClass> <name> )
{
<catch block>}
8. Finally clause
•
A try statement can have an optional clause designated by
the reserved word finally.
• If no exception is generated, the statements in the finally
clause are executed after the statements in the try block
complete.
try {
// statements that throw exceptions
} catch(<exception>) {
// do stuff
} finally {
– // code here runs whether or not catch runs
}
9. Throw
All methods use the throw statement to throw an exception.
The throw statement requires a single argument: a throwable object.
Throwable objects are instances of any subclass of the Throwable class. Here's
an example of a throw statement.