RPGCode — Language Features — Error handling
Contents
Error handlingError handling
RPGCode has an error handling mechanism built-in to help you catch certain errors that you may want to handle differently than normal. One common example of implementing error handling into a program is by creating a fileExists() function. You may want to check whether a file has been created or not before trying to read from or write to it. It can be done like this:
function fileExists(file, folder) { setErrorHandler(:error); openFileInput(file, folder); closeFile(file); return true; :error return false; }
This function first sets the error handler to :error
(a label). When an error is raised inside the function, it will be caught by the error handler and will jump to the :error label near the bottom of the function. In this particular function, an error will be raised if file in folder does not exist and the function will return false
; otherwise the function will return true
.
Another error handling function, setResumeNextHandler()
, may also be used to circumvent errors altogether, and it may be combined with setErrorHandler()
to section off code that might raise an error and code that shouldn't. Here is an example of using it with the fileExists()
function:
function fileExists(file, folder) { setErrorHandler(:error); openFileInput(file, folder); setResumeNextHandler(); closeFile(file); return true; :error return false; }
Here we use setResumeNextHandler()
after the potentially erroneous code. Any error after this point will not be caught. (Note that because the function returns after we jump to the :error label anyway, setResumeNextHandler()
isn't particularly useful here.) Another function that exists is resumeNext()
, which can be used to jump back to the line after the error.
A caveat of the current error handling implementation is that it cannot catch errors in nested functions. For example, in the following code, the potential error that's raised by nonexistentFile()
will not be ignored by func()
, even though it uses setResumeNextHandler()
:
function nonexistentFile() { openFileInput("anonexistentfile", ""); } function func() { setResumeNextHandler(); nonexistentFile(); }
Because of the way error handling is implemented, it cannot be used outside of functions. (You also shouldn't need to use it outside of a function; jumping to labels can be very messy and create unmaintainable code — use this only where it's necessary!)
Alternative syntax
For backwards compatibility, an alternative syntax is provided for error handling. Here is the fileExists()
function as an example:
function fileExists(file, folder) { on error goto :error openFileInput(file, folder); on error resume next closeFile(file); return true; :error return false; }
It is recommended that you use the error handling functions rather than this alternative syntax.