before() ; method() ; after() before() try { method() } finally { after() }
interface Widget { void ping(int pongs) }
class OldWidget implements Widget { . . . } class NewWidget implements Widget { private OldWidget oldWidget; NewWidget(OldWidget ow) { oldWidget = ow } void ping(int pongs) { before() ; oldWidget.ping(pongs) ; after() } }
class OldWidget implements Widget { . . . } class NewWidget extends OldWidget { void ping(int pongs) { before() ; super.ping(pongs) ; after() } }
abstract class Widget void operation() { before() ; function() ; after() } abstract void before() abstract void function() abstract void after()
class UnsynchronizedWidget extends Widget { void before() { } void function() { // whatever } void after() { } } class Synchronizedwidget extends Widget { void before() { mutex.lock() } void function() { // whatever } void before() { mutex.unlock() } }
interface CheckWidget bool check(Widget w)
class UnsynchronizedWidgetCheck implements WidgetCheck bool check(Widget w) return w.check() class SynchronizedWidgetCheck implements WidgetCheck void check(Widget w) synchronized (w) { return w.check() }
Runnable
-run()
is another example.
assert
bool-expr [ :
value-expr ] ;
void
expression.
bool-expr
is true, nothing happens.
bool-expr
is false, throw an Assertion Error
exception.
value-expr
is given, the exception carries the value it
produces.
-source 1.4
command-line option.
javac
assumes pre-1.4 Java source.
-ea
(enable assertion) argument.
java
does not do assertion checking.
$ cat a.java class a { public static void main(String[] args) { try { assert false : "Oopsie, an assertion failed!"; } catch (AssertionError ae) { System.out.println("Caught an assertion failure: " + ae.getMessage()); } } } $ javac a.java a.java:3: warning: as of release 1.4, assert is a keyword, and may not be used as an identifier try { assert false : "Oopsie, an assertion failed!"; } ^ a.java:3: not a statement try { assert false : "Oopsie, an assertion failed!"; } ^ a.java:3: ';' expected try { assert false : "Oopsie, an assertion failed!"; } ^ 2 errors 1 warning $ javac -source 1.4 a.java $ java a $ java -ea a Caught an assertion failure: Oopsie, an assertion failed! $
try
-catch
-finally
finally
clause is always executed.
try
, finally
.
try
, exception, catch
, finally
.
try
, exception, catch
, exception, finally
.
try
, exception, finally
.
try { mutex.lock() // whatever } catch (InterruptedExecution ie) { // whatever } finally { mutex.unlock() }
catch
clauses are optional.
finally
clause always executes.
This page last modified on 22 July 2002.