Object-oriented exception handling system

Exceptions are objects in Cyan like in many Object-Oriented Languages. All exception prototypes should inherit from prototype Exception from package cyan.lang.

The novelty here is that exceptions are thrown and caught by message passings. An exception is thrown using method throw: declared in prototype Any, the top-level prototype:

if n < 0 { throw: ExceptionStr("negative!") }

Before understanding how to catch exceptions, it is important to know how to declare and call methods that use several ‘method keywords’:

object Demo func at: Int n { ... } func at: Int n at: Int p { ... } func at: Int n at: Int p at: Int k { ... } end

This prototype defines three methods. The first has one Cyan keyword, at:. The second, two keywords, at: and at:, resulting in the selector at:at:. The last method has three at: keywords. These methods are called as in this example:

var d = Demo(); d at: 0; d at: 0 at: 1; d at: 0 at: 1 at: 2;

One instance of a function that does not takes parameters is used below.

var f = { 0 println }; // prints 0 f eval;

We are going to translate a code that handles exceptions in Java to Cyan. The Java code is this:

int n = -1; try { if (n < 0) { throw new ExceptionStr("n < 0"); } if (n == 0) { throw new ExceptionExit(); } } catch( ExceptionStr e ) { System.out.println("Exception ExceptionStr was thrown"); } catch( ExceptionExit e ) { System.out.println("Exception ExceptionExit was thrown"); }

The Cyan code is this:

var Int n = -1; // try-catch is in fact a message send { if n < 0 { // an exception is thrown by sending // message 'throw:' to self // Exceptions must inherit from cyan.lang.CyException // ExceptionStr is in package cyan.lang throw: ExceptionStr("n < 0"); } if n == 0 { // use the prototype as the // exception object throw: ExceptionExit; } } // this is the end of the anonymous function catch: { (: ExceptionStr e :) "Exception ExceptionStr was thrown" println } catch: { (: ExceptionExit e :) "Exception ExceptionExit was thrown" println } ;

Message catch: ... catch: ... is sent to the anonymous function that starts on line 3. The arguments to the catch: selectors are anonymous functions too, they correspond to the statements of catch clauses of conventional languages like C++ or Java.

In Cyan, there may be hierarchies of exception treatments, not only hierarchies of exception prototypes. This is because the anonymous functions that are parameters to the catch: selectors may be grouped into prototypes (see the Cyan manual for more details). Hence, we could have an object CatchStrExit with two methods called eval:, each one with the body of each anonymous functions that are arguments in the previous code.

var Int n = -1; { // as before } catch: CatchStrExit;