Exceptions
Table of Contents
1 Motivation
1.1 Non-local returns
How do we exit a for
loop in C
when an error occurs?
for(i=0;i<10;i++){ if ( error ) { break; } } /* execution resumes here after break */
However, in a nested loop, break
exits only from the innermost
loop.
for(i=0;i<10;i++){ for(j=0;j<10;j++){ if ( error ) { break; } } /* execution resumes here after break */ }
What if when an error happens, we want to exit from some arbitrary level in the loop? This is not easy. The programmer can carefully manage it with the help of flags. Suppose, in the following code, when an error happens in the third nested level, we want to resume the loop at the first level (not the second). Then we can do this with the help of flags.
for(i=0;i<10;i++){ for(j=0;j<10;j++){ for(k=0; k<10; k++){ if ( error ) { flag=1; break; } } /* execution resumes here after break in k*/ if(flag){ flag = 0; /* clear flag */ break; } } /* execution resumes here after break in j*/ }
1.2 Error-handling in code
When we code defensively, we need to check whether each statement in the code may lead to an error. This leads to code in which the main logic is obscured.
int main() { FILE * fp = fopen ("testfile", r); int val; int i; if (!fp) { printf("File did not open successfully\n"); return OPEN_ERROR; } val = fscanf(fp, "%d", &i); if (!val){ printf ("Value could not be read\n"); return READ_ERROR; } ... }
Is there an elegant mechanism to handle such situations?
2 Exceptions
(try <s1> catch <x> then <s2> end, E)
Actions.
- Push
(catch <x> then <s2> end, E)
onto the semantic stack. - Push
(<s1>,E)
onto the semantic stack
raise <y> end
- Pop all statements on the semantic stack until the first
(catch <x> then <s> end, E')
is found. - Push
(<s>, E' + {X-><y>})
onto the stack.