User-specified Error Handling¶
The try-catch combination loosely clones similar routines in C++. Within the brackets following each may be any collection of G7 routines, including other try-catch blocks. If execution of any of the s within the try block produces an internal error signal, or if a user-specified error is thrown with the return , then execution of the code in the try block ceases and execution of the code in the catch block begins. Otherwise, the catch block is ignored. For example, consider the link-series ls. The routine will fail if the value of the guide series is zero in the base period. Ordinarily, this will cause G7 to stop execution of the script and report an error. If, on the other hand, the ls is nested within a try block, then if an error occurs the alternative block of code following the catch will be executed. In the following example, suppose that we prefer to use guide series y when it is available, and when it is not we rely on guide series z. We first try to extend series x using series y beginning in 2005, and if the value of y is zero in 2005, then we repeat the exercise using series ‘z’:
try{
ls x y 2005 f
}
catch{
try{
ls x z 2005 f
}
catch{
ic Sorry. No data in y or z.
pause
}
}
The try-catch routine works well with many other s and has a wide variety of useful applications. Note again that try-catch blocks can be nested, so that several alternatives can be tried before G7 gives up in despair.
Often, anticipated errors alternatively can be handled with if-else routines. For example, the f will fail if a right-hand-side variable is not found. G7 can handle such failures elegantly either by nesting the f in a try block or by using the if , with the exists function, to test for the availability of the variable before attempting to use it.