Module std::condition

Condition handling

Conditions are a utility used to deal with handling error conditions. The syntax of a condition handler strikes a resemblance to try/catch blocks in other languages, but condition handlers are not a form of exception handling in the same manner.

A condition is declared through the condition! macro provided by the compiler:

condition! {
    pub my_error: int -> ~str;
}

This macro declares an inner module called my_error with one static variable, cond that is a static Condition instance. To help understand what the other parameters are used for, an example usage of this condition would be:

do my_error::cond.trap(|raised_int| {

    // the condition `my_error` was raised on, and the value it raised is stored
    // in `raised_int`. This closure must return a `~str` type (as specified in
    // the declaration of the condition
    if raised_int == 3 { ~"three" } else { ~"oh well" }

}).inside {

    // The condition handler above is installed for the duration of this block.
    // That handler will override any previous handler, but the previous handler
    // is restored when this block returns (handlers nest)
    //
    // If any code from this block (or code from another block) raises on the
    // condition, then the above handler will be invoked (so long as there's no
    // other nested handler).

    println(my_error::cond.raise(3)); // prints "three"
    println(my_error::cond.raise(4)); // prints "oh well"

}

Condition handling is useful in cases where propagating errors is either to cumbersome or just not necessary in the first place. It should also be noted, though, that if there is not handler installed when a condition is raised, then the task invokes fail!() and will terminate.

More Info

Condition handlers as an error strategy is well explained in the conditions tutorial, along with comparing and contrasting it with other error handling strategies.

Structs

Condition

This struct represents the state of a condition handler. It contains a key into TLS which holds the currently install handler, along with the name of the condition (useful for debugging).