| 1 |
/* |
| 2 |
* test of catching a run-time exception |
| 3 |
*/ |
| 4 |
|
| 5 |
#include "tads.h" |
| 6 |
#include "t3.h" |
| 7 |
|
| 8 |
function main(args) |
| 9 |
{ |
| 10 |
local ret; |
| 11 |
|
| 12 |
test_catch_1(); |
| 13 |
test_catch_2(); |
| 14 |
|
| 15 |
ret = test_catch_3(nil); |
| 16 |
"back in _main: test_catch_3(nil) = <<ret>>\n"; |
| 17 |
|
| 18 |
ret = test_catch_3(true); |
| 19 |
"back in _main: test_catch_3(true) = <<ret>>\n"; |
| 20 |
} |
| 21 |
|
| 22 |
class Exception1: Exception |
| 23 |
construct(msg) { msg_ = msg; } |
| 24 |
msg_ = '' |
| 25 |
display = "This is an Exception1 with message \"<<msg_>>\"" |
| 26 |
; |
| 27 |
|
| 28 |
modify RuntimeError |
| 29 |
display { tadsSay(exceptionMessage); "\n"; } |
| 30 |
; |
| 31 |
|
| 32 |
function test_catch_1() |
| 33 |
{ |
| 34 |
"test catch 1 - catch our own throw\n"; |
| 35 |
try |
| 36 |
{ |
| 37 |
"about to throw our error...\n"; |
| 38 |
throw new Exception1('hello!'); |
| 39 |
|
| 40 |
"??? can't be here\n"; |
| 41 |
} |
| 42 |
catch (Exception1 ex) |
| 43 |
{ |
| 44 |
"test catch 1 - caught Exception1: << ex.display >>\n"; |
| 45 |
} |
| 46 |
catch (Exception th) |
| 47 |
{ |
| 48 |
"test catch 1 - caught Exception: << th.display >>\n"; |
| 49 |
} |
| 50 |
finally |
| 51 |
{ |
| 52 |
"test catch 1 - in finally\n"; |
| 53 |
} |
| 54 |
} |
| 55 |
|
| 56 |
function test_catch_2() |
| 57 |
{ |
| 58 |
"test catch 2 - catching a VM error\n"; |
| 59 |
|
| 60 |
try |
| 61 |
{ |
| 62 |
local i; |
| 63 |
|
| 64 |
"about to generate an error...\n"; |
| 65 |
i = 1; |
| 66 |
i = i + 'x'; |
| 67 |
|
| 68 |
"??? shouldn't get here!"; |
| 69 |
} |
| 70 |
catch (Exception th) |
| 71 |
{ |
| 72 |
"test catch 2 - caught Exception: << th.display >>\n"; |
| 73 |
} |
| 74 |
finally |
| 75 |
{ |
| 76 |
"test catch 2 - in finally\n"; |
| 77 |
} |
| 78 |
} |
| 79 |
|
| 80 |
function test_catch_3(do_err) |
| 81 |
{ |
| 82 |
"test catch 3 - catching an error while computing a return value\n"; |
| 83 |
|
| 84 |
try |
| 85 |
{ |
| 86 |
"calculating our return value...\n"; |
| 87 |
return maybe_gen_err(do_err); |
| 88 |
} |
| 89 |
catch (Exception th) |
| 90 |
{ |
| 91 |
"test catch 3 - caught Exception: << th.display >>\n"; |
| 92 |
"returning 'error'\n"; |
| 93 |
return 'error'; |
| 94 |
} |
| 95 |
} |
| 96 |
|
| 97 |
function maybe_gen_err(do_err) |
| 98 |
{ |
| 99 |
"... in maybe_gen_err\n"; |
| 100 |
if (do_err) |
| 101 |
{ |
| 102 |
local i; |
| 103 |
|
| 104 |
"... causing a run-time error\n"; |
| 105 |
i = 0; |
| 106 |
i = 1/i; |
| 107 |
} |
| 108 |
|
| 109 |
"... returning 'okay'\n"; |
| 110 |
return 'okay'; |
| 111 |
} |
| 112 |
|