-
Notifications
You must be signed in to change notification settings - Fork 0
Catching and Throwing Errors
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:
- Check that the file exists.
- Check it's readable as text.
- Check the file isn't locked.
- ...
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.
Algo (c) Larry Tang, 2019.
Commercial use of Algo must include the LICENSE
file in the same directory as the executable.
Standard Library Documentation: