try-catch-finally
The combination of try, catch and finally is used to execute code in a try block, deal with exceptional circumstances in a catch block, and perform cleanup or final actions in a finally block. catch and finally are optional. Note that the finally block will always be performed if it exists.
General Form
try { stmt } catch (Exception e) { exception handling } finally { cleanup }
Example
{ try { int dividend = randI(11); int divisor = randI(3); pln(dividend, "/", divisor, " = ", dividend/divisor); } catch (Exception e) { pln(eRed, e.description, ePop); } finally { pln("Division attempt was successful"); } }
do-finally
The combination of do and finally is used to execute code in a do block and perform cleanup or final actions in a finally block. Note that the finally block will always be performed unless an exception is raised in the do block.
General Form
do { stmt } finally { cleanup }
Example
{ int steps = 200; ProgressDialog dialog = beginProgress(anyFrameWindow, steps, modal=true); do { for (j in 1..steps) { if (dialog.aborted) break; sleep(20); incrProgress(); } } finally { endProgress(); } }
throw
If a problem occurs it may be useful to throw an exception for this rather than just avoiding the problem. Subroutines can throw exceptions that are then handled in try..catch..finally clauses by methods calling the subroutines. You can throw exceptions that are subclasses of the class Exception.
Examples
public class APolyline2D extends AShape2D { .. /** * Close the polyline. */ public void close() { if (!_closed) { if (points.count > 0) { points << points[0]; _closed = true; } else { throw CantHappen("Cannot close polyline : no points added."); } } } .. }
{ try { int dividend = randI(11); int divisor = randI(3); pln(dividend, "/", divisor, " = ", dividend/divisor); } catch (Exception e) { if (developMode) throw e; else pln(eRed, e.description, ePop); } finally { pln("Division attempt was successful"); } }
Comments
0 comments
Please sign in to leave a comment.