A Tour of Morfa

Try-catch-finally

Morfa has a standard try-catch-finally construct for dealing with computations that may throw exceptions. For example, as many things may go wrong when writing text to a file, various parts of the following routine are wrapped in try-catch and try-catch-finally:

import morfa.io.device.File;
import morfa.io.format.TextEncoder;
import morfa.io.print;

func writeToFile(path: text, textToWrite: text, encoding: text = "UTF-8")
{
    try 
    {
        var file = new File(path, "w");
        try 
        {
            var encoder = new TextEncoder(file, encoding);
            encoder.writeAll(textToWrite);
        }
        catch (e: WriteError) // catches errors in writeAll()
        {
            println("Cannot write to file: " ~ e.toText());
        }
        catch (t: Throwable) // a catch-all clause
        {
            println("Something went wrong: " ~ t.toText());
        }       
        finally 
        {
            file.close();
        }
    }
    catch (e: StreamError) // let other types of exceptions escape
    {
        println("Cannot open file: " ~ e.toText());
    }
}

unittest
{
    // This should report 'Cannot open file' (unless you're root):
    writeToFile("/root/output.txt", "Hello!\n");
    // This should state that 'Something went wrong':
    writeToFile("output.txt", "Hello again!\n", "STRANGE_ENCODING");
    // This should write to 'output.txt':
    writeToFile("output.txt", "Finally got it right!\n");
}

The catch clause if valid only if the type of the caught object is a subclass of Throwable.

The order of catch clauses is important: a clause that precedes another (in a single try-catch) must cover a type of exception that is strictly more specific than the type covered by the following clause. For example, if we swapped the catch clause for WriteError with the one for Throwable, then not only you would not be able to catch the more specific WriteError exception but the code would not compile.

Throw

To throw an exception (an object deriving from Throwable) do throw new MyException().