Exception Statements in Java

The throw Statement:
A throw statement has the form
throw expression;

where the type of the expression must be a subtype of class Throwable . The throw statement is executed as follows: The expression is evaluated to obtain an exception object v. If it is null, then a NullPointerException is thrown; otherwise the exception object v is thrown. Thus a thrown
exception is never null. In any case, the enclosing block statement terminates abruptly .

The thrown exception may be caught in a dynamically enclosing try-catch statement . If the exception is not caught, then the entire program execution will be aborted, and information from the exception will be printed on the console (for example, at the command prompt, or in the Java Console inside a Web browser.

The try-catch-finally Statement:
A try-catch statement is used to catch (particular) exceptions thrown by the execution of a block of code. It has the following form:
try
body
catch (El x1) catchbody1
catch (E2 x2) catchbody2
...
finally finallybody

whereE1, E2 ,.. are names of exception types, x1, x2,.. are variable names,and body,catchbodyi, and finallybody are block-statements . There can be zero or more catch clauses, and the finally clause may be absent, but at least one catch or finally clause must be present.We say that Ei matches exception type E if E is a subtype of Ei (possibly equal to Ei).

The try-catch-finally statement is executed by executing the body. If the execution of the body
terminates normally, or exits by return or break or continue (when inside a method or constructor or switch or loop), then the catch clauses are ignored. If the body terminates abruptly by throwing exception e of class E, then the first matching Ei (if any) is located, variable xi is bound to e, and the corresponding catchbodyi is executed. The catchbodyi may terminate normally, or loop, or exit by executing return or break or continue, or throw an exception (possibly xi); if there is no finally clause, this determines how the entire try-catch statement terminates. A thrown exception e is never null , so xi is guaranteed not to be null either. If there is no matching Ei, then the entire try-catch statement terminates abruptly with exception e.


If there is a finally clause,then finallybody will be executed regardless of whether the execution of body terminated normally, regardless of whether body exited by executing return or break or
continue (when inside a method or constructor or switch or loop), regardless of whether any
exception thrown by body was caught by a catch clause, and regardless of whether the catch clause exited by executing return or break or continue or by throwing an exception. If execution of finallybody terminates normally, then the entire try-catch-finally terminates as determined by body (or catchbodyi, if one was executed and terminated abruptly or exited). If execution of finallybody terminates abruptly, then that determines how the entire try-catch-finally terminates .

The assert Statement:
The assert statement has one of the following forms:

assert boolean-expression ;
assert boolean-expression : expression ;

The boolean-expression must have type boolean. The expression must have type boolean, char,
double, float, int, long, or Object.

Under ordinary execution of a program, an assert statement has no effect at all. However, assertions may be enabled at run-time by specifying the option -ea or -enableassertions when executing a program C :

java -enableassertions C

When assertions are enabled at run-time, every execution of the assert statement will evaluate the boolean-expression. If the result is true, program execution continues normally. If the result is false, the assertion fails and an Assertion Error will be thrown; moreover, in the second form of the assert statement, the expression will be evaluated and its value will be passed to the appropriate Assertion Error constructor. Thus the value of the expression will be reported along with the exception in case of assertion failure. This simplifies troubleshooting in a malfunctioning program.


An Assertion Error signals the failure of a fundamental assumption in the program and should not be caught by a try-catch statement in the program; it should be allowed to propagate to the top level. An assert statement can serve two purposes: to document the programmer's assumption about the state at a certain point in the program, and to check (at run-time) that that assumption holds (provided the program is executed using the enableassertions option).

One may put an assert statement after a particularly complicated piece of code, to check that it has achieved what it was supposed to

Using assert to Specify and Check the Result of an Algorithm:

The integer square root of x ≥ 0 is an integer y such that y2 ≤ x and (y + 1)2 > x. The precondition x ≥ 0 is always checked, using an if statement. The postcondition on y is specified by an assert statement, and checked if assertions are enabled at run-time — which is reassuring, given that the correctness is none too obvious. The assertion uses casts to long to avoid arithmetic overflow.


static int sqrt(int x) { // Algorithm by Borgerding, Hsieh, Ulery

if (x < y =" 0," b =" 0x8000," bshft =" 15," v =" x;;">= (temp = (y<<1)+b>>= 1) > 0);
assert (long)y * y <= x && (long)(y+1)*(y+1) > x;
return y;
}

In a class that has a data representation invariant, one may assert the invariant at the end of every method in the class .

Using assert to Specify and Check Invariants:
A word list is a sequence of words to be formatted a line of text. Its length is the minimum number of characters needed to format the words and the interword spaces, that is, the lengths of the words plus the number of words minus 1. Those methods that change the word list use assert statements to specify the invariant on length and check it if assertions are enabled at run-time.


class WordList {
private LinkedList strings = new LinkedList();

private int length = -1; // Invariant: equals word lengths plus interword spaces
public int length() { return length; }
public void addLast(String s) {
strings.addLast(s);
length += 1 + s.length();
assert length == computeLength() + strings.size() - 1;
}
public String removeFirst() {
String res = (String)strings.removeFirst();
length -= 1 + res.length();
assert length == computeLength() + strings.size() - 1;
return res;
}
private int computeLength() { ... } // For checking the invariant only
}

One should not use assert statements to check the validity of user input or the arguments of public methods or constructors, because the check would be performed only if assertions are enabled at runtime.Instead, use ordinary if statements and throw an exception in case of error.
The assert statement was introduced in Java 2, version 1.4, and cannot be used in Java compilers prior to that. A program using the assert statement must be compiled with option -
source 1.4, as follows:


javac -source 1.4 myprog.java

An algorithm for formatting a sequence of words into a text with a straight right-hand margin should produce lines res of a specified length lineWidth, unless there is only one word on the line or the line is the last one. This requirement can be expressed and checked using an assert statement :


assert res.length()==lineWidth || wordCount==1 || !wordIter.hasNext();

RELATED POST:

JAVA STATEMENTS PART TWO

No comments:

Post a Comment