Docsity

Java: Defensive Programming with Assertions & Exceptions, Study notes of Computer Science

Toggle sidebar
bg1
Assertions and Exceptions in Java
Reed, CS340, Fall 2004
Examples and notes taken in large part from:
http://6170.lcs.mit.edu/www-archive/Old-2004-Spring/lectures/handout/L11-assertions.pdf
Defensive Programming
public double sqrt (double x)
// requires: x >= 0
// returns: approximation to square root of x { ... }
Suppose this is called with a negative number, and you want to guard against this:
public double sqrt (double x)
// requires: x >= 0
// returns: approximation to square root of x
{
if (! (x >= 0))
throw new AssertionError ();
...
}
Assertions in programming languages are generally called with a procedure called assert that
guarantees a condition at runtime, e.g.
assert (x >= 0);
Uses for Assertions
These can be used both for precondition as well as postcondition checks. E.g. a postcondition
check for a value to be roughly correct in calculating square root:
public double sqrt (double x)
// requires: x >= 0
// returns: approximation to square root of x
{
assert (x >= 0);
double r;
... // compute result r
assert ( Math.abs(r*r - x) < .0001 );
return r;
}
See [https://www.cis.strath.ac.uk/teaching/ug/classes/52.361/2003/representation.pdf ] for a
discussion of representation invariants (aka rep invariants).
Covering all cases: uses assertion to block illegal cases.
switch (cardSuit) {
case CLUBS: return "clubs";
case DIAMONDS: return "diamonds";
case HEARTS: return "hearts";
case SPADES: return "spades";
default: assert(false);
pf3
pf4
pf5

Partial preview of the text

Download Java: Defensive Programming with Assertions & Exceptions and more Study notes Computer Science in PDF only on Docsity!

Assertions and Exceptions in Java

Reed, CS340, Fall 2004 Examples and notes taken in large part from: http://6170.lcs.mit.edu/www-archive/Old-2004-Spring/lectures/handout/L11-assertions.pdf

Defensive Programming

public double sqrt (double x) // requires: x >= 0 // returns: approximation to square root of x { ... } Suppose this is called with a negative number, and you want to guard against this: public double sqrt (double x) // requires: x >= 0 // returns: approximation to square root of x { if (! (x >= 0)) throw new AssertionError (); ... } Assertions in programming languages are generally called with a procedure called assert that guarantees a condition at runtime, e.g. assert (x >= 0);

Uses for Assertions

These can be used both for precondition as well as postcondition checks. E.g. a postcondition check for a value to be roughly correct in calculating square root: public double sqrt (double x) // requires: x >= 0 // returns: approximation to square root of x { assert (x >= 0); double r; ... // compute result r assert ( Math.abs(rr - x) < .0001 );* return r; } See [https://www.cis.strath.ac.uk/teaching/ug/classes/52.361/2003/representation.pdf ] for a discussion of representation invariants (aka rep invariants ). Covering all cases: uses assertion to block illegal cases. switch (cardSuit) { case CLUBS: return "clubs"; case DIAMONDS: return "diamonds"; case HEARTS: return "hearts"; case SPADES: return "spades"; default: assert(false);

} Write assertions as you type in your code, not afterwards.

What not to assert

It takes time to run each assertion. Avoid: // don’t do this x = y + 1; assert (x == y+1); Use assertions only to find internal logic errors in your code. Use Exceptions to handle errors external to your program, such as a missing file. Don’t put any program actions inside an assert: // don’t do this assert (list.remove (x)); If assertions are disabled, the entire expression is skipped, and x is never removed from the list. Write it like this instead: boolean found = list.remove (x); assert (found);

Assertions in Java

In Java 1.4 run-time assertions are built-in. E.g. assert x >= 0; An assert statement may also include a description expression, which is usually a string, but may also be a primitive type or a reference to an object. The description is printed in an error message when the assertion fails, so it can be used to provide additional details to the programmer about the cause of the failure. The description follows the asserted expression, separated by a colon. For example: assert (x >= 0) : "x is " + x; If x = -1, then this assertion fails with the error message x is - The exception passes along an object which stores additional information about what happened and at what point in your program it happened. This information provides a stack trace that tells you where the assert statement was found in your code and the sequence of calls that arrived there. This information is often enough to get started in finding the bug. E.g. java.lang.IllegalArgumentException at sqrt(Sqrt.java:13) at testSqrt(SqrtTest.java:51) ... at main(TestRunner.java:29) Assert is not recognized by the compiler at all unless you add a command line switch: javac -source 1.4 MyClass.java Additionally, even though assertions may have passed the compiler, when running your program assertions are by default disabled (for efficiency). To enable assertions when running your program you must use: java -ea MyClass

Exceptions for Special Results

An exception keeps getting passed down the stack along the call sequence until it finds a method that has a matching handler. For instance the solveQuad() method reuses the sqrt() method. If an IllegalArgumentException is thrown inside sqrt(), that exception can be passed through solveQuad() until it finds a matching handler, or gets all way out, which terminates the program (or thread). double solveQuad (double a, double b, double c) throws IllegalArgumentException // returns: x such that ax^2 + bx + c = 0 // throws: IllegalArgumentException if no real soln exists { return (-b + sqrt (bb - 4ac)) / (2a); } Code can be written to provide exception translation , where a thrown exception (e.g. IllegalArgumentException) can be translated into a throw of an exception that we create, called NotRealException double solveQuad (double a, double b, double c) throws NotRealException // returns: x such that ax^2 + bx + c = 0 // throws: NotRealException if no real solution exists { try { return (-b + sqrt (bb - 4ac)) / (2a); } catch (IllegalArgumentException e) { throw new NotRealException (); } } For this to work we make our own class called NotRealException , which is a subclass of Exception. class NotRealException extends Exception { NotRealException () { super (); } NotRealException (String msg) { super (msg); } } All exceptions may have a string message associated with them, which is why NotRealException has two constructors. If not provided in the constructor, the message is null. An exception is a full-fledged object, however, so you are free to add additional fields and methods to an exception which provide more information about the failure or special result.

Checked vs. Unchecked Exceptions

Checked exceptions must be declared in the method signature, and are enforced by the compiler. An example of this is IOException. Unchecked exceptions can occur at any time and do not need to appear in the method signature. NullPointerException and IllegalArgumentException are examples. The complete class hierarchy for Java exceptions is shown below:

 Throwable is the class of objects that can be thrown or caught. Any object used in a throw or catch statement, or declared in the throws clause of a method, must be a subclass of Throwable. Throwable’s implementation records a stack trace at the point where the exception was thrown, along with an optional string describing the exception.  Error is a subclass of Throwable that is “reserved” for errors produced by the Java runtime system, such as StackOverflowError and OutOfMemoryError. For some reason, AssertionError also extends Error, even though it indicates a failure in user code, not in the Java runtime. Errors should be considered unrecoverable, and are generally not caught.  Errors and RuntimeExceptions are unchecked. All other Throwables and Exceptions are checked. You can’t tell just by looking at the code whether an exception is checked or unchecked, so it is important to document this.