]> git.lizzy.rs Git - metalua.git/blob - src/samples/trycatch_test.mlua
added a try...catch...with extension
[metalua.git] / src / samples / trycatch_test.mlua
1 -{ extension 'trycatch' }
2
3
4 ----------------------------------------------------------------------
5 print "1) no error"
6 try
7    print("   Hi")
8 end
9
10
11 ----------------------------------------------------------------------
12 print "2) caught error"
13 try
14    error "some_error"
15 catch x ->
16    printf("   Successfully caught %q", x)
17 end
18
19
20 ----------------------------------------------------------------------
21 print "3) no error, with a finally"
22 try
23    print "   Hi"
24 finally
25    print "   Finally OK"
26 end
27
28
29 ----------------------------------------------------------------------
30 print "4) error, with a finally"
31 try
32    print "   Hi"
33    error "bang"
34 catch "bang" ->
35    -- nothing
36 finally
37    print "   Finally OK"
38 end
39
40
41 ----------------------------------------------------------------------
42 print "5) nested catchers"
43 try
44    try
45       error "some_error"
46    catch "some_other_error" ->
47       assert (false, "mismatch, this must not happen")
48    end
49 catch "some_error"/x ->
50    printf("   Successfully caught %q across a try that didn't catch", x)
51 | x ->
52    assert (false, "We shouldn't reach this catch-all")
53 end
54
55
56 ----------------------------------------------------------------------
57 print "6) nested catchers, with a 'finally in the inner one"
58 try
59    try
60       error "some_error"
61    catch "some_other_error" ->
62       assert (false, "mismatch, this must not happen")
63    finally
64       print "   Leaving the inner try-catch"
65    end
66 catch "some_error"/x ->
67    printf("   Successfully caught %q across a try that didn't catch", x)
68 | x ->
69    assert (false, "We shouldn't reach this catch-all")
70 end
71
72
73 ----------------------------------------------------------------------
74 print "7) 'finally' intercepts a return from a function"
75 function f()
76    try
77       print "   into f:"
78       return "F_RESULT"
79       assert (false, "I'll never go there")
80    catch _ ->
81       assert (false, "No exception should be thrown")
82    finally
83       print "   I do the finally before leaving f()"
84    end
85 end
86 local fr = f()
87 printf("   f returned %q", fr)
88
89
90 ----------------------------------------------------------------------
91 print "*) done."