Skip to content

Catching and Throwing Errors

C272 edited this page Dec 18, 2019 · 5 revisions

Occasionally, you may expect errors when you execute a statement, but don't want to end the program. For this, there is the "try catch" statement, which will stop execution when it finds an error, and instead of ending the program, will simply pass the error message on into the catch block. Here's an example of how that would work:

try
{
    let x = IDontExist; //fails, so skips to the catch block
    print "done"; //this is never executed
}
catch(e)
{
    print e; //prints "No variable exists named 'IDontExist'."
}

It is generally bad practice to include lots of try/catch statements in your code ("defensive programming"), but it is better to ask forgiveness for an error rather than ask permission in Algo. For example, if you wanted to safely open a file that the user provided, you could:

  1. Check that the file exists.
  2. Check it's readable as text.
  3. Check the file isn't locked.
  4. ...

Or, you could do this:

import "io"; //for input.get()

while (true)
{
    print "Enter a file to open!";
    let file = input.get();
    let fileContent = "";
    try {
        fileContent = input.fromFile(file);
        break; //continues on
    }
    catch(e)
    {
        print "Invalid file! Please try again.";
    }
}

The second one is arguably easier, and saves a lot of headaches and edge cases. So, use sparingly but well.