Professional Documents
Culture Documents
DSC 6 10
DSC 6 10
DSC 6 10
DSC-6-10
Handling
An condition that arises in a code sequence at run time, In other words, an
exception is a run-time error.
Java’s exception handling avoids these problems and, in the process, brings
run-time error management into the object-oriented world.
Exceptions
Origin:
Unexpected conditions
That method may choose to handle the exception itself, or pass it on.
Exceptions can be generated by the Java run-time system, or they can be manually
generated by our code.
Exceptions thrown by Java relate to fundamental errors that violate the rules of the Java
language or the constraints of the Java execution environment.
Exceptions Types
ClassNotFoundException
IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException
VirtualMachineError
Error
AWTError
IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException
VirtualMachineError
Error
AWTError
ClassNotFoundException
IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException
VirtualMachineError
Error
RuntimeException is caused by
AWTError
programming errors, such as bad
casting, accessing an out-of-bounds
Several more classes array, and numeric errors.
Types of Exceptions
• Errors - serious and fatal problems
9
Checked Exceptions vs. Unchecked Exceptions
RuntimeException, Error and their subclasses are known as
unchecked exceptions.
All other exceptions are known as checked exceptions - the
compiler forces the programmer to check and deal with the
exceptions.
Checked or Unchecked Exceptions
ClassNotFoundException
IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException
VirtualMachineError
Error
Unchecked
AWTError
exception.
12
Exceptions
Exception handling is managed via five keywords: try, catch, throw, throws, and finally.
Program statements that we want to monitor for exceptions are contained within a try
block, if an exception occurs within the try block, it is thrown.
The code can catch this exception (using catch) and handle it in some rational manner.
System-generated exceptions are automatically thrown by the Java run-time system.
To manually throw an exception, use the keyword throw, any exception that is thrown out
of a method must be specified as such by a throws clause.
Any code that absolutely must be executed after a try block completes is put in a finally
block
try-catch
Default exception handling is useful for debugging, you will usually want to handle an
exception yourself, doing so provides two benefits:
First, it allows you to fix the error, and Second, it prevents the program from automatically
terminating.
Sometimes a program stops running and prints a stack trace whenever an error occurs, it is
quite easy to prevent this using the try block.
Immediately following the try block, include a catch clause that specifies the exception
type that you wish to catch.
try-catch
class Exc2 {
public static void main(String args[]) {
int d, a;
catch (ArithmeticException e) {
// catch divide-by-zero error
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}
throw
We catch exceptions that are thrown by the Java run-time system, However, it is possible
for your program to throw an exception explicitly, using the throw statement.
Primitive types, such as int or char, as well as non-Throwable classes, such as String and
Object, cannot be used as exceptions.
There are two ways you can obtain a Throwable object: using a parameter in a catch
clause, or creating one with the new operator.
throw
The flow of execution stops immediately after the throw statement; any subsequent
statements are not executed.
The nearest enclosing try block is inspected to see if it has a catch statement that matches
the type of exception.
If it does find a match, control is transferred to that statement, If not, then the next
enclosing try statement is inspected, and so on.
If no matching catch is found, then the default exception handler halts the program and
prints the stack trace.
throw
class ThrowDemo {
static void demoproc() {
try {
throw new NullPointerException("demo");
}
catch(NullPointerException e) {
System.out.println("Caught inside demoproc.");
throw e; // rethrow the exception
}
}
public static void main(String args[]) {
try {
demoproc();
}
catch(NullPointerException e) {
System.out.println("Recaught: " + e);
}}}
throws
If a method is capable of causing an exception that it does not handle, it must specify this
behavior so that callers of the method can guard themselves against that exception.
A throws clause lists the types of exceptions that a method might throw.
This is necessary for all exceptions, except those type Error or RuntimeException, or any of
their subclasses.
All other exceptions that a method can throw must be declared in the throws clause, If
they are not, a compile-time error will result.
finally
When exceptions are thrown, execution in a method takes a rather abrupt, nonlinear path
that alters the normal flow through the method.
Depending upon how the method is coded, it is even possible for an exception to cause
the method to return prematurely.
This could be a problem in some methods, for example, if a method opens a file upon
entry and closes it upon exit, then you will not want the code that closes the file to be
bypassed by the exception-handling mechanism.
The finally keyword is designed to address this contingency, it creates a block of code that
will be executed after a try/catch block has completed and before the code following the
try/catch block.
finally
The finally block will execute whether or not an exception is thrown.
If an exception is thrown, the finally block will execute even if no catch statement matches
the exception.
Any time a method is about to return to the caller from inside a try/catch block, via an
uncaught exception or an explicit return statement, the finally clause is also executed just
before the method returns.
This can be useful for closing file handles and freeing up any other resources that might
have been allocated at the beginning of a method with the intent of disposing of them
before returning.
The finally clause is optional. However, each try statement requires at least one catch or a
finally clause.
Checked Exceptions
Checked exceptions that can be thrown in a method must be
• caught and handled
OR
• declared in the throws clause
22
Declaring Exceptions
Every method must state the types of checked exceptions it might throw.
This is known as declaring exceptions.
23
Throwing Exceptions
When the program detects an error, the program can create an
instance of an appropriate exception type and throw it.
24
Throwing Exceptions Example
/** Set a new radius */
public void setRadius(double newRadius)
throws IllegalArgumentException {
if (newRadius >= 0)
radius = newRadius;
else
throw new IllegalArgumentException(
"Radius cannot be negative");
}
Catching Exceptions
try {
statements; // Statements that may throw exceptions
}
...
catch (ExceptionN exVar3) {
handler for exceptionN;
}
Catch or Declare Checked Exceptions
If a method declares a checked exception, you must invoke it in a try-catch block
or declare to throw the exception in the calling method.
(a) (b)
27
Exceptions in GUI Applications
The methods are executed on the threads, If an exception occurs on a thread, the
thread is terminated if the exception is not handled.
However, the other threads in the application are not affected, there are several
threads running to support a GUI application.
If an exception occurs during the execution of a GUI event handler, the thread is
terminated if the exception is not handled.
Java prints the error message on console, but does not terminate the application.
The program goes back to its user-interface-processing loop to run continuously.
28
The finally Clause
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
29
animation
Trace a Program Execution
Suppose no
exceptions in the
statements
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
30
animation
Trace a Program Execution
Next statement;
31
animation
Trace a Program Execution
Next statement;
32
animation
Trace a Program Execution
Next statement;
33
animation
Trace a Program Execution
Next statement;
34
animation
Trace a Program Execution
Next statement;
35
animation
Trace a Program Execution
Next statement;
36
animation
Trace a Program Execution
try {
statement1; statement2 throws an
statement2; exception of type
statement3; Exception2.
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Next statement;
37
animation
Trace a Program Execution
try {
statement1; Handling exception
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Next statement;
38
animation
Trace a Program Execution
try {
statement1; Execute the final block
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Next statement;
39
animation
Trace a Program Execution
try {
statement1; Rethrow the exception
statement2; and control is
statement3; transferred to the caller
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Next statement;
40
Cautions When Using Exceptions
• Exception handling separates error-handling code from
normal programming tasks, thus making programs
easier to read and to modify.
• Exception handling usually requires more time and
resources because it requires instantiating a new
exception object, rolling back the call stack, and
propagating the errors to the calling methods.
41
When to Throw Exceptions
• An exception occurs in a method.
• If you want the exception to be processed by its caller,
you should create an exception object and throw it.
• If you can handle the exception in the method where it
occurs, there is no need to throw it.
42
When to Use Exceptions
When should you use the try-catch block in the code?
You should use it to deal with unexpected error
conditions. Do not use it to deal with simple, expected
situations. For example, the following code
try {
System.out.println(refVar.toString());
}
catch (NullPointerException ex) {
System.out.println("refVar is null");
}
43
When to Use Exceptions
is better to be replaced by
if (refVar != null)
System.out.println(refVar.toString());
else
System.out.println("refVar is null");
44
Creating Custom Exception Classes
45
Exceptions and Generics
• A generic class cannot extend Throwable.
• An Exception cannot be of a generic type.
46
Exceptions and Inheritance
How do you think exceptions affect overridden methods?
• if a method overrides a base class method, the new method cannot
throw a more general error, but can throw more specific
• if the base class method throws no errors, the subclass method can't
either.
47
Assertions
An assertion is a Java statement that enables you
to assert an assumption about your program.
48
Declaring Assertions
An assertion is declared using the new Java keyword
assert in JDK 1.4 as follows:
assert assertion; or
assert assertion : detailMessage;
49
Assertions
• If an assertion evaluates true, there are no effects.
50
Executing Assertions Example
public class AssertionDemo {
public static void main(String[] args) {
int i; int sum = 0;
for (i = 0; i < 10; i++) {
sum += i;
}
assert i == 10;
assert sum > 10 && sum < 5 * 10 : "sum is " + sum;
}
}
51
Running Programs with Assertions
By default, the assertions are disabled at runtime. To
enable it, use the switch –enableassertions, or –ea for
short, as follows:
53
Using Exception Handling or
Assertions
Assertion should not be used to replace exception handling.
Like exception handling, assertions are not used for normal tests, but
for internal consistency and validity checks.
54
Using Exception Handling or
Assertions, cont.
Use assertions to reaffirm assumptions. This gives you
more confidence to assure correctness of the program.
A common use of assertions is to replace assumptions
with assertions in the code.
55
Using Exception Handling or
Assertions, cont.
Another good use of assertions is place assertions in a
switch statement without a default case. For example,
switch (month) {
case 1: ... ; break;
case 2: ... ; break;
...
case 12: ... ; break;
default: assert false : "Invalid month: " + month
}
56