6.Exception Handling

Download Report

Transcript 6.Exception Handling

Exception Handling
1
Objectives
After completing this chapter, the student will be able to:
•
•
•
•
•
Explain Java exceptions
Explain predefined Java exceptions
Write simple programs with proper exception
handling
Create his/her own exceptions in a Java
program
Explain exception propagation
2
Objectives contd..
•
•
•
•
•
Write Java programs in which exceptions are
propagated to higher levels
Explain Assertions
Use Assertions in your code
Compile files that use Assertions
Enable and Disable Assertions in your code
3
Introduction
•
Exceptions are some important or unexpected events
that can occur in the course of execution of a
program.
•
If exceptions are not handled properly the program
will meet with an abrupt end with an error message
thrown to you.
•
Exception handling means diverting the processing
to a part of the program when an exception occurs.
4
Predefined Exception
•
Predefined exceptions are set in motion when your
program does some illegal or invalid action.
•
When a predefined exception occurs, the Java run
time system will create a predefined exception
object.
5
Predefined Exception hierarchy
Object
◦ Throwable
 Error
 Exception
Error
◦ VirtualMachineError
 StackOverflowError
 OutOfMemoryError
◦ AssertionError
6
Predefined Exception hierarchy contd..

Exception
◦ RuntimeException
 ArithmeticException
 NullPointerException
 IllegalArgumentException
◦
◦
◦
◦
SQLException
IOException
ClassNotFoundException
NoSuchMethodException
7
Predefined Exception contd..
Triggering a Predefined Exception
•
A predefined exception is generated when your
program does some illegal operation.
•
In a java program integer division-by-zero is an
illegal operation.
•
It caused an exception and the program came to an
abrupt halt with an error message thrown to you.
8
Predefined Exception contd..
Handling the Exception
•
The exception thrown in the a program can be
captured and handled properly.
•
Throwing an exception is equivalent to a break
statement.
•
The statement below the point where exception
occurred in the try-catch segment will not be
executed.
9
Predefined Exception contd..
The try-catch Construct
•
•
•
•
•
The try-catch construct is the technique used to capture
and handle exceptions. The statements between try and
catch will be executed.
The group of statements between the try-catch clauses
may be generating several exceptions.
While executing , if an exception occurs which matches
with the argument of catch, the statements in the curly
braces that follow the catch keyword will be executed.
After executing these statements, the program will
continue with the next statement.
If the exception created does not match with the argument
of catch , it will be propagated to the calling environment.
10
User Created Exceptions
•
Exceptions can be set in motion explicitly by the user
with the throws statement.
•
The throw statement has the following format:
throw ExceptionObject
•
The ExceptionObject is an object of the class that
extends Exception class.
•
Any method that throws a user-defined exception
must also catch the exception.
11
Handling Related Exceptions
•
Exception thrown should match with the argument
exception of the catch clause.
•
Exception thrown can be a subclass of the argument
exception.
12
Handling Group of Related Exceptions
•
A group of exception objects, all derived from the
same exception class can be caught and assigned to
a single class.
•
It is the same as the parent class.
13
Exception Propagation
•
An exception should be handled in the method in
which it is thrown.
•
In case it is not handled in the method in which it was
thrown, the method’s signature should be modified
so that the caller of this method is forewarned about
the exception.
•
Ex:
public void method() throws ExceptionObject {
……..
}
14
The Finally Clause
•
To perform some action absolutely , no matter
whatever happens while executing a group of
statements.
•
The group of statements enclosed between try and
finally clause can create exception.
• There can be a break statement.
• There can be a continue statement.
• There can be a return statement.
•
In any case the group of statements in the finally
clause will be executed.
15
Assertion
Introduction
•
An assertion is a statement in the Java programming
language. It enables you to test your assumptions
about your program.
•
It’s introduced in java 1.4 release.
•
Assertions provide a convenient mechanism for
verifying that a class’s methods are called correctly.
•
This mechanism can be enabled and disabled at
runtime.
16
Assertion contd..
Assert Statement
•
•
The assertion statement has two forms. The first,
simpler form is: assert Expression1 ;
When the system runs the assertion, it evaluates
Expression1.
If it is false throws an AssertionError with no detail
message.
The second form is:
assert Expression1 : Expression2;
When the system runs the assertion, it evaluates
Expression1.
If it is false throws an AssertionError with detail
message(Expression2).
17
Assertion contd..
Assert Statement
•
•
•
•
•
If assertions are disabled at runtime the assert
statement does absolutely nothing.
If assertions are enabled at runtime then Expression1
is evaluated.
If its value is true, no further action is taken.
If its value is false, then an AssertionError is thrown.
If Expression2 is present ,it is passed into the
constructor of the AssertionError, where it is converted
to a String and used as the error message.
18
Assertion contd..
Putting Assertions into Your Code
•
In the following situations it is good to use assertions.
• Internal Invariants
• Control-Flow Invariants
• Preconditions, Postconditions
• and Class Invariants
•
It should not be use in the following situations:
• Do not use assertions for argument checking in
public methods
• Do not use assertions to do any work that your
application requires for correct operation.
19
Assertion contd..
Internal Invariants
•
•
Before assertions were available, comments were
used to indicate their assumptions concerning a
program's behavior.
You might have written something like this to explain
your assumption about an else clause in a multiway
if-statement:
if (i % 3 == 0) {
...
} else if (i % 3 == 1) {
...
} else { // We know (i % 3 == 2)
...
}
20
Assertion contd..
Internal Invariants
•
You should now use an assertion whenever you
would have written a comment that asserts an
invariant.
if (i % 3 == 0) {
...
} else if (i % 3 == 1) {
...
} else {
assert (i%3==2):i;
...
}
21
Assertion contd..
Preconditions and Postconditions
Preconditions:
• By convention, preconditions on public methods are
enforced by explicit checks that throw particular,
specified exceptions.
•
This convention is unaffected by the addition of the
assert construct.
Postconditions:
• Postconditions can be test with assertions in both
public and nonpublic methods.
•
It is necessary to save some data prior to performing
a computation in order to check a postcondition.
22
Assertion contd..
Compiling Files That Use Assertions
•
In order for the javac compiler to accept code
containing assertions, you must use the -source 1.4
command-line option:
javac -source 1.4 MyClass.java
•
This flag is necessary so as not to cause source
compatibility problems.
23
Assertion contd..
Enabling and Disabling Assertions
•
By default, assertions are disabled at runtime.
•
Two command-line switches allow you to selectively
enable or disable assertions.
•
To enable assertions at various granularities, use the
-enableassertions, or -ea, switch.
•
To disable assertions at various granularities, use the
-disableassertions, or -da, switch.
24
Assertion contd..
Enabling and Disabling Assertions
Arguments to switch :
•
•
•
•
No arguments – in all classes except system classes.
Packagename – in the named package and any sub
packages.
… - in the unnamed package in the current working
directory.
className – in the named class.
25