Chapter_4_Exceptions_Assertions_Errors

Download Report

Transcript Chapter_4_Exceptions_Assertions_Errors

Errors, Exceptions , Assertions: Overview
Introduction:
During execution, a program can run into many kinds of errors. Error
detection and handling are the two most important factors in making a
programming language robust.
In Java, exceptions provide a clean and simple way to check for error
conditions.
Assertions are used to document and validate assumptions made in the
program. They are used to implement correct programs whereas
Exceptions are used to implement robust programs.
Both these mechanisms used together, facilitate programs that are
reliable.
1
Errors, Exceptions and Assertions :
Overview
Objective:
After completing this Topic, you will be able to, make proper use of
exceptions,recognize the effect of exceptions and errors, and make proper
use of assertions.
Topics involved in this module :
1. Knowing Java exceptions/errors and their hierarchy.
2. Stack based exception propagation
3. Putting together the try-catch-finally block
4. Clause : throws/throw
5. Runtime Exceptions
6. Creating user defined exception class
7. Exception Handling in overridden methods
2
Knowing Java exceptions/errors,
hierarchy
Java Exceptions
•
•
•
•
•
An Exception in Java is a signal that indicates the occurrence of some
unexpected condition during execution.
Provide a simple and a clean way to detect and handle errors generated in the
program.
Also cleanly separates the error-generating code and the error-handling code.
Facilitate creation of robust programs.
They are derived directly from the java.lang.Throwable class.
3
Knowing Java exceptions/errors
Throwable
class
Exception hierarchy
• Two subclasses of the
Throwable class : Exception
and Error.
• The Error class and its sub
classes represent situations
that are not caused by anything
that is a part of the normal
program flow.
• Errors are never explicitly
handled and the program
cannot recover from an Error.
• An exception can be explicitly
handled and a program
execution flow can recover from
an Exception.
Exception
class
Error class
Assertion
Error
Runtime
Exceptions
Checked
exceptions
Fig 4.1
4
Knowing Java exceptions/errors
•
Exception class can be further classified as Runtime Exceptions and Checked
Exceptions.
Runtime Exceptions :
•
Runtime Exceptions are faults in the program detected at runtime by the system.
Eg. ArrayIndexOutOfBoundException, ArithmeticException etc.
Checked Exceptions
•
•
All exceptions except the Runtime exceptions and Errors are termed as Checked
Exceptions.
A method that can throw a checked exception , directly or indirectly, must
explicitly handle it, which means that the method must either catch the exception
and take the proper action, or it must pass the exception to its caller.
5
Stack based exception propagation
Understanding the runtime stack of a thread.
• Each thread executing in the JVM has its own runtime stack (call
stack).
• Corresponding to every method call is an activation record - an
element on the call stack.
• A method call results in its activation record being pushed on to
the stack.
• On the completion of its execution, this record is popped from the
stack and the execution control goes back to the caller method.
• The contents of a the call stack comprise of the stack trace of a
program execution.
6
Stack based exception propagation
class Division {
public void divide(int firstNumber, int secondNumber){
int result = 0;
result = firstNumber/secondNumber;
System.out.println(“Result is : ” + result);
}
public static void main(String args[])
{
Division d = new Division();
d.divide(10, 0);
}
}
7
Stack based exception propagation
ArithmeticException.
divide() completes
abruptly
divide’s activation
record
main’s activation
record
Call stack - 1
main’s activation
record
Call stack - 2
divide’s activation
Record popped out
ArithmeticException
passed to main.
main() completes
abruptly
main’s activation
record
main’s activation
record
Call stack - 3
Call stack - 4
Fig 4.2
Exception
propagated to main’
default exception
handler
main’s activation
record Popped out
Call stack - 5
8
Putting together the try-catch-finally block
•
The exception handling mechanism
follows the try-catch-finally construct.
Using the try-catch-finally
blocks
•
•
•
The exceptions generated in the tryblock are caught and handled in the
corresponding catch-block.
A single try-block can have zero or
more catch-blocks, but only one
finally-block.
A try-block must be followed either by
at least one catch-block or one
finally-block.
try {
<statements> //try block
}
catch(<ExceptionType1>
<parammeter1>){
<statements> //catch block
}
...
catch(<ExceptionTypeN>
<parammeterN>){
<statements> //catch block
}
finally {
<statements> //finally
block
}
9
Putting together the try-catch-finally block
try-block
– Contains the code that might
generate exceptions.
– If an exception occurs, control is
transferred to the catch block.
– If the try block execution is
successful, control is transferred
to the finally block.
catch-block
– The catch block contains an
Exception-type parameter in its
header. It deals with all the
exceptions and sub-classes of
this declared type.
– After a catch block is executed,
the control is transferred to the
finally block.
Without any
exception
try {}
ExceptionType2
ExceptionType1
catch
ExceptionType1
catch
ExceptionType2
finally
block
10
Putting together the try-catch-finally block
finally-block
• The finally-block is always executed before the control is
transferred to its final destination.
• Different scenarios of execution in the finally block
– If no exception is thrown during the execution of the try block or the exception
has been caught in a catch block.
– If there is any pending exception thrown in the try-block and not handled.
– If the finally-block throws an exception.
– If the finally block executes a control transfer statement such as return or
labeled break.
11
Putting together the try-catch-finally block
Putting together the try-catch-finally block in a method
void myMethod(int firstNum, int secondNum, int index ){
int result[5];
try {
result[index] = firstNum/secondNum;
//line 1
}
catch(ArrayIndexOutOfBoundException e){
//line 2
System.out.println(“Exception in myMethod():”+ e);
}
catch(ArithmeticException e){
System.out.println(“Exception in myMethod():”+ e);
}
finally{
System.out.println(“In finally block”);
}
}
12
Clause : throw/throws
The throw clause
• A method can
explicitly throw an
exception using the
throw statement.
public class ThrowDemo{
public int division(int firstNumber, int
secondNumber){
if(secondNumber == 0)
throw new ArithmeticException("Divide
by zero error");
//line 1
return firstNumber/secondNumber;
}
public static void main(String args[]){
ThrowDemo d = new ThrowDemo();
try{
d.division(12,0);
}
catch(ArithmeticException ae){
System.out.println(ae);
}
}
– throw <Throwable
class reference
expression>;
– E.g. throw new
ArithmeticException
(“Divide by zero”);
}
13
Clause : throw/throws
The throws clause
•
•
public class ThrowsDemo{
public void myMethod() throws
InterruptedException {
Specifies all the checked
exceptions that a method
may throw.
…someMethod(…)
throws <Exception
Type1>, <Exception
Type2>, … <Exception
TypeN> {
/* method body */
}
throw new
InterruptedException("Throws
Demo exception");
}
public static void main(String
args[]){
ThrowsDemo d = new ThrowsDemo();
try{
d.myMethod();
}
catch(InterruptedException ie){
System.out.println(ie);
}
}
• A method can throw
only those exceptions
which are declared in
its throws clause.
}
14
Runtime Exceptions
• Represent problems that are detected by the runtime system.
• Example :
– arithmetic exception like divide by zero
– pointer exceptions like accessing an object through a null reference
• Generated by faults in the methods or by the JVM itself.
• Also called unchecked exceptions, meaning that methods need not
catch or specify them.
• Create a subclass of RuntimeException when representing an error
in the virtual machine runtime, otherwise subclass Exception.
15
Creating user-defined exception class
• Allow customized exceptions to be thrown and caught as normal
exceptions.
• To create unchecked exceptions sub class RuntimeException
class.
• To create checked exceptions sub class Exception class.
Template
class myException extends Exception
{
myException () { }
//default Constructor
myException (String message) { //Parameterized Constructor
super(message);
}
/* Provide overridden toString() method */
}
16
Creating user-defined exception class
class CapacityExceededException extends Exception{ } //new exception
public class Bag {
int itemIndex;
public void fillBag(int storeItem) throws
CapacityExceededException {
if(itemIndex > 20)
throw new CapacityExceededException();
itemIndex++;
}
public static void main(String args[]){
int i;
Bag b = new Bag();
try{
for(i = 0 ; i < 30 ; i++)
b.fillBag(i);
}catch(CapacityExceededException ce){
System.out.println(ce);
}
} }
17
Exception Handling in overridden
methods
Overriding methods cannot specify more checked exceptions in its
throws clause than the overridden method does.
• Example
import java.io.*;
class Base{
public void myMethod() throws IOException,
ClassCastException{ }
}
class Derived extends Base {
public void myMethod() throws IOException { }
/*
Not Allowed
public void myMethod() throws InterruptedException { }
*/
}
18
Assertion Mechanism
•
•
•
•
•
Facilitate creation of correct
programs.
Used to validate assumptions about
the state of the program at specified
locations in the code.
Contains a boolean expression that
is expected to be true when
executed.
– If false, the system throws
AssertionError.
Can be enabled or disabled at
runtime.
Two forms of assert statement :
/*simple form*/
assert <boolean expression> ;
/*augmented form*/
assert <boolean expression> :
<message expression> ;
If assertions
are enabled
Evaluate boolean
expression
If true
If false
Throw an
AssertionError
Normal execution
continues
Execution is
aborted
19
Assertion Mechanism
Compiling Assertions
• > javac –source 1.4 <programName.java>
Runtime Enabling and Disabling of Assertions
• By default assertions are disabled.
• Switch –enableassertions , or –ea - Enable the assertions.
• Switch –disableassertions , or –da - Disable the assertions.
-ea
-da
Applies to all non-system classes.
-ea: <package name>…
-da: <package name>…
Applies to the named package and its
subpackages.
-ea: …
-da: …
Applies to the unnamed package in the
current working directory.
-ea:<class name>
-da:<class name>
Applies the named class.
20
Assertion Mechanism
A complete assertions example:
class Square {
int length;
Square()
{
length = -1;
}
public int area() {
int area;
assert (length >= 0) : “Length is Negative" ;
area = (length)*(length);
}
}
1. javac –source 1.4 Square.java
2. java –ea Square
3. java.lang.AssertionError: Length is Negative is thrown.
21
Errors, Exceptions and Assertions :
Summary
•
An Exception in Java is a signal that indicates the occurrence of some
unexpected condition during execution.
• Exception and Error class are derived from java.lang.Throwable class.
•
•
The Java exceptions mechanism is based on try-catch-finally construct.
One can explicitly throw an exception using throw keyword.
•
And a method must specify all the checked exceptions it throws using the
throws keyword.
By extending the Exception class, user-defined exceptions can be created.
•
•
•
•
Assertions are used to validate assumptions about the state of the program at
specified locations in the code.
Assertions can be enabled or disabled at runtime at various levels of granularity.
Assertions are used to generate programs that are correct and exceptions are
used to generate programs that are robust. Together these two mechanisms
make Java programs reliable.
22
: Quiz
•
•
•
•
•
•
What is the difference between an exception and an assertion ?
Why are runtime exceptions not caught explicitly in a method?
How are exceptions propagated up the runtime stack?
Explain the throw-catch paradigm.
Can a main method declare that it throws checked exceptions?
What happens on compiling and running the following program ?
class Demo {
public static void main(String args[]) {
RuntimeException exc = null;
throw exc;
}
}
• Given the following command , which classes will have assertions
enabled
java –ea –da:package1… package2.myPackage.myClass.
23
24