Jamie Balfour

Welcome to my personal website.

Find out more about me, my personal projects, reviews, courses and much more here.

Official ZPE/YASS documentationTry-catch statements

Official ZPE/YASS documentationTry-catch statements

Version 1.4.3.40 introduced Try-Catch statements and made the way that ZPE handles errors much simpler, leading to an open function for throwing all errors. With the introduction of the Try-Catch statement, ZPE 1.4.3.40 opened a whole world of possibilities for throwing errors.

When an error is thrown and a Try-Catch statement surrounds this, the error is handled by the program. The following example shows a list of two elements but the user attempts to access a third, causing an error.

YASS
$l = [32, 55]
try
  //Attempt to access third element
  list_get_at_index($l, 2)
end try
        

Since a third element does not exist the program would crash, but since it is wrapped in the Try statement (line 2), the program execution continues. In this next example, the program does not just continue but it takes a different route down the Catch route.

YASS
$l = [32, 55]
try
  //Attempt to access third element
  list_get_at_index($l, 2)
catch
  std_err("Attempted to access an invalid index")
end try
        

Since most built-in functions have error messages that they send upward, it is useful to observe these messages. To do this, the Catch statement is given a variable. This variable will be given a value if the error occurs and will be visible only within the Catch statement.

YASS
$l = [32, 55]
try
  //Attempt to access third element
  list_get_at_index($l, 2)
catch($exception)
  //Version 1.7.x onwards
  std_err($exception->get_message())
  //Earlier than version 1.7.x
  //std_err($exception())
end try
        

In this case, the application is designed to print the error message found in $exception to the standard error output stream.

If $exception was defined before the Catch statement, it will automatically be reset to it's value that was stored in it after the Catch statement closes.

Finally, as with most statements in YASS, Try-Catch statements can use braces like Java and C instead of the end try based structure. The following is the same program with the brace structure:

YASS
$l = [32, 55]
try {
  //Attempt to access third element
  list_get_at_index($l, 2)
} catch($exception->get_message()) {
  std_err($exception)
}
        
Comments
Feedback 👍
Comments are sent via email to me.