test_try_except.py 23.1 KB
Newer Older
dugupeiwen's avatar
dugupeiwen committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
import warnings
import dis
from itertools import product

import numpy as np

from numba import njit, typed, objmode, prange
from numba.core.utils import PYVERSION
from numba.core import ir_utils, ir
from numba.core.errors import (
    UnsupportedError, CompilerError, NumbaPerformanceWarning, TypingError,
)
from numba.tests.support import (
    TestCase, unittest, captured_stdout, MemoryLeakMixin,
    skip_parfors_unsupported, skip_unless_scipy, expected_failure_py311
)


class MyError(Exception):
    pass


class TestTryBareExcept(TestCase):
    """Test the following pattern:

        try:
            <body>
        except:
            <handling>
    """
    def test_try_inner_raise(self):
        @njit
        def inner(x):
            if x:
                raise MyError

        @njit
        def udt(x):
            try:
                inner(x)
                return "not raised"
            except:             # noqa: E722
                return "caught"

        self.assertEqual(udt(False), "not raised")
        self.assertEqual(udt(True), "caught")

    def test_try_state_reset(self):
        @njit
        def inner(x):
            if x == 1:
                raise MyError("one")
            elif x == 2:
                raise MyError("two")

        @njit
        def udt(x):
            try:
                inner(x)
                res = "not raised"
            except:             # noqa: E722
                res = "caught"
            if x == 0:
                inner(2)
            return res

        with self.assertRaises(MyError) as raises:
            udt(0)
        self.assertEqual(str(raises.exception), "two")
        self.assertEqual(udt(1), "caught")
        self.assertEqual(udt(-1), "not raised")

    def _multi_inner(self):
        @njit
        def inner(x):
            if x == 1:
                print("call_one")
                raise MyError("one")
            elif x == 2:
                print("call_two")
                raise MyError("two")
            elif x == 3:
                print("call_three")
                raise MyError("three")
            else:
                print("call_other")

        return inner

    def test_nested_try(self):
        inner = self._multi_inner()

        @njit
        def udt(x, y, z):
            try:
                try:
                    print("A")
                    inner(x)
                    print("B")
                except:         # noqa: E722
                    print("C")
                    inner(y)
                    print("D")
            except:             # noqa: E722
                print("E")
                inner(z)
                print("F")

        # case 1
        with self.assertRaises(MyError) as raises:
            with captured_stdout() as stdout:
                udt(1, 2, 3)
        self.assertEqual(
            stdout.getvalue().split(),
            ["A", "call_one", "C", "call_two", "E", "call_three"],
        )
        self.assertEqual(str(raises.exception), "three")

        # case 2
        with captured_stdout() as stdout:
            udt(1, 0, 3)
        self.assertEqual(
            stdout.getvalue().split(),
            ["A", "call_one", "C", "call_other", "D"],
        )

        # case 3
        with captured_stdout() as stdout:
            udt(1, 2, 0)
        self.assertEqual(
            stdout.getvalue().split(),
            ["A", "call_one", "C", "call_two", "E", "call_other", "F"],
        )

    def test_loop_in_try(self):
        inner = self._multi_inner()

        @njit
        def udt(x, n):
            try:
                print("A")
                for i in range(n):
                    print(i)
                    if i == x:
                        inner(i)
            except:             # noqa: E722
                print("B")
            return i

        # case 1
        with captured_stdout() as stdout:
            res = udt(3, 5)
        self.assertEqual(
            stdout.getvalue().split(),
            ["A", "0", "1", "2", "3", "call_three", "B"],
        )
        self.assertEqual(res, 3)

        # case 2
        with captured_stdout() as stdout:
            res = udt(1, 3)
        self.assertEqual(
            stdout.getvalue().split(),
            ["A", "0", "1", "call_one", "B"],
        )
        self.assertEqual(res, 1)

        # case 3
        with captured_stdout() as stdout:
            res = udt(0, 3)
        self.assertEqual(
            stdout.getvalue().split(),
            ["A", "0", "call_other", "1", "2"],
        )
        self.assertEqual(res, 2)

    def test_raise_in_try(self):
        @njit
        def udt(x):
            try:
                print("A")
                if x:
                    raise MyError("my_error")
                print("B")
            except:             # noqa: E722
                print("C")
                return 321
            return 123

        # case 1
        with captured_stdout() as stdout:
            res = udt(True)

        self.assertEqual(
            stdout.getvalue().split(),
            ["A", "C"],
        )
        self.assertEqual(res, 321)

        # case 2
        with captured_stdout() as stdout:
            res = udt(False)

        self.assertEqual(
            stdout.getvalue().split(),
            ["A", "B"],
        )
        self.assertEqual(res, 123)

    def test_recursion(self):
        @njit
        def foo(x):
            if x > 0:
                try:
                    foo(x - 1)
                except:   # noqa: E722
                    print("CAUGHT")
                    return 12
            if x == 1:
                raise ValueError("exception")

        with captured_stdout() as stdout:
            res = foo(10)

        self.assertIsNone(res)
        self.assertEqual(stdout.getvalue().split(), ["CAUGHT",],)

    def test_yield(self):
        @njit
        def foo(x):
            if x > 0:
                try:
                    yield 7
                    raise ValueError("exception")   # never hit
                except Exception:
                    print("CAUGHT")

        @njit
        def bar(z):
            return next(foo(z))

        with captured_stdout() as stdout:
            res = bar(10)

        self.assertEqual(res, 7)
        self.assertEqual(stdout.getvalue().split(), [])

    def test_closure2(self):
        @njit
        def foo(x):
            def bar():
                try:
                    raise ValueError("exception")
                except:  # noqa: E722
                    print("CAUGHT")
                    return 12
            bar()

        with captured_stdout() as stdout:
            foo(10)

        self.assertEqual(stdout.getvalue().split(), ["CAUGHT",],)

    def test_closure3(self):
        @njit
        def foo(x):
            def bar(z):
                try:
                    raise ValueError("exception")
                except:  # noqa: E722
                    print("CAUGHT")
                    return z
            return [x for x in map(bar, [1, 2, 3])]

        with captured_stdout() as stdout:
            res = foo(10)

        self.assertEqual(res, [1, 2, 3])
        self.assertEqual(stdout.getvalue().split(), ["CAUGHT",] * 3,)

    def test_closure4(self):
        @njit
        def foo(x):
            def bar(z):
                if z < 0:
                    raise ValueError("exception")
                return z

            try:
                return [x for x in map(bar, [1, 2, 3, x])]
            except:  # noqa: E722
                print("CAUGHT")

        with captured_stdout() as stdout:
            res = foo(-1)

        self.assertEqual(stdout.getvalue().strip(), "CAUGHT")
        self.assertIsNone(res)

        with captured_stdout() as stdout:
            res = foo(4)
        self.assertEqual(stdout.getvalue(), "")
        self.assertEqual(res, [1, 2, 3, 4])

    @skip_unless_scipy
    def test_real_problem(self):
        @njit
        def foo():
            a = np.zeros((4, 4))
            try:
                chol = np.linalg.cholesky(a)
            except:  # noqa: E722
                print("CAUGHT")
                return chol

        with captured_stdout() as stdout:
            foo()

        self.assertEqual(stdout.getvalue().split(), ["CAUGHT",])

    def test_for_loop(self):
        @njit
        def foo(n):

            for i in range(n):
                try:
                    if i > 5:
                        raise ValueError
                except:  # noqa: E722
                    print("CAUGHT")
            else:
                try:
                    try:
                        try:
                            if i > 5:
                                raise ValueError
                        except:  # noqa: E722
                            print("CAUGHT1")
                            raise ValueError
                    except:  # noqa: E722
                        print("CAUGHT2")
                        raise ValueError
                except:  # noqa: E722
                    print("CAUGHT3")

        with captured_stdout() as stdout:
            foo(10)

        self.assertEqual(
            stdout.getvalue().split(),
            ["CAUGHT",] * 4 + ["CAUGHT%s" % i for i in range(1, 4)],
        )

    def test_try_pass(self):
        @njit
        def foo(x):
            try:
                pass
            except:     # noqa: E722
                pass
            return x

        res = foo(123)
        self.assertEqual(res, 123)

    def test_try_except_reraise(self):
        @njit
        def udt():
            try:
                raise ValueError("ERROR")
            except:    # noqa: E722
                raise

        with self.assertRaises(UnsupportedError) as raises:
            udt()
        self.assertIn(
            "The re-raising of an exception is not yet supported.",
            str(raises.exception),
        )


class TestTryExceptCaught(TestCase):
    def test_catch_exception(self):
        @njit
        def udt(x):
            try:
                print("A")
                if x:
                    raise ZeroDivisionError("321")
                print("B")
            except Exception:
                print("C")
            print("D")

        # case 1
        with captured_stdout() as stdout:
            udt(True)

        self.assertEqual(
            stdout.getvalue().split(),
            ["A", "C", "D"],
        )

        # case 2
        with captured_stdout() as stdout:
            udt(False)

        self.assertEqual(
            stdout.getvalue().split(),
            ["A", "B", "D"],
        )

    def test_return_in_catch(self):
        @njit
        def udt(x):
            try:
                print("A")
                if x:
                    raise ZeroDivisionError
                print("B")
                r = 123
            except Exception:
                print("C")
                r = 321
                return r
            print("D")
            return r

        # case 1
        with captured_stdout() as stdout:
            res = udt(True)

        self.assertEqual(
            stdout.getvalue().split(),
            ["A", "C"],
        )
        self.assertEqual(res, 321)

        # case 2
        with captured_stdout() as stdout:
            res = udt(False)

        self.assertEqual(
            stdout.getvalue().split(),
            ["A", "B", "D"],
        )
        self.assertEqual(res, 123)

    def test_save_caught(self):
        @njit
        def udt(x):
            try:
                if x:
                    raise ZeroDivisionError
                r = 123
            except Exception as e:  # noqa: F841
                r = 321
                return r
            return r

        with self.assertRaises(UnsupportedError) as raises:
            udt(True)
        self.assertIn(
            "Exception object cannot be stored into variable (e)",
            str(raises.exception)
        )

    def test_try_except_reraise(self):
        @njit
        def udt():
            try:
                raise ValueError("ERROR")
            except Exception:
                raise

        with self.assertRaises(UnsupportedError) as raises:
            udt()
        self.assertIn(
            "The re-raising of an exception is not yet supported.",
            str(raises.exception),
        )

    def test_try_except_reraise_chain(self):
        @njit
        def udt():
            try:
                raise ValueError("ERROR")
            except Exception:
                try:
                    raise
                except Exception:
                    raise

        with self.assertRaises(UnsupportedError) as raises:
            udt()
        self.assertIn(
            "The re-raising of an exception is not yet supported.",
            str(raises.exception),
        )

    def test_division_operator(self):
        # This test that old-style implementation propagate exception
        # to the exception handler properly.
        @njit
        def udt(y):
            try:
                1 / y
            except Exception:
                return 0xdead
            else:
                return 1 / y

        self.assertEqual(udt(0), 0xdead)
        self.assertEqual(udt(2), 0.5)


class TestTryExceptNested(TestCase):
    "Tests for complicated nesting"

    def check_compare(self, cfunc, pyfunc, *args, **kwargs):
        with captured_stdout() as stdout:
            pyfunc(*args, **kwargs)
        expect = stdout.getvalue()

        with captured_stdout() as stdout:
            cfunc(*args, **kwargs)
        got = stdout.getvalue()
        self.assertEqual(
            expect, got,
            msg="args={} kwargs={}".format(args, kwargs)
        )

    def test_try_except_else(self):
        @njit
        def udt(x, y, z, p):
            print('A')
            if x:
                print('B')
                try:
                    print('C')
                    if y:
                        print('D')
                        raise MyError("y")
                    print('E')
                except Exception: # noqa: F722
                    print('F')
                    try:
                        print('H')
                        try:
                            print('I')
                            if z:
                                print('J')
                                raise MyError('z')
                            print('K')
                        except Exception:
                            print('L')
                        else:
                            print('M')
                    except Exception:
                        print('N')
                    else:
                        print('O')
                    print('P')
                else:
                    print('G')
                print('Q')
            print('R')

        cases = list(product([True, False], repeat=4))
        self.assertTrue(cases)
        for x, y, z, p in cases:
            self.check_compare(
                udt, udt.py_func,
                x=x, y=y, z=z, p=p,
            )

    def test_try_except_finally(self):
        @njit
        def udt(p, q):
            try:
                print('A')
                if p:
                    print('B')
                    raise MyError
                print('C')
            except:             # noqa: E722
                print('D')
            finally:
                try:
                    print('E')
                    if q:
                        print('F')
                        raise MyError
                except Exception:
                    print('G')
                else:
                    print('H')
                finally:
                    print('I')

        cases = list(product([True, False], repeat=2))
        self.assertTrue(cases)
        for p, q in cases:
            self.check_compare(
                udt, udt.py_func,
                p=p, q=q,
            )


class TestTryExceptRefct(MemoryLeakMixin, TestCase):
    def test_list_direct_raise(self):
        @njit
        def udt(n, raise_at):
            lst = typed.List()
            try:
                for i in range(n):
                    if i == raise_at:
                        raise IndexError
                    lst.append(i)
            except Exception:
                return lst
            else:
                return lst

        out = udt(10, raise_at=5)
        self.assertEqual(list(out), list(range(5)))
        out = udt(10, raise_at=10)
        self.assertEqual(list(out), list(range(10)))

    def test_list_indirect_raise(self):
        @njit
        def appender(lst, n, raise_at):
            for i in range(n):
                if i == raise_at:
                    raise IndexError
                lst.append(i)
            return lst

        @njit
        def udt(n, raise_at):
            lst = typed.List()
            lst.append(0xbe11)
            try:
                appender(lst, n, raise_at)
            except Exception:
                return lst
            else:
                return lst

        out = udt(10, raise_at=5)
        self.assertEqual(list(out), [0xbe11] + list(range(5)))
        out = udt(10, raise_at=10)
        self.assertEqual(list(out), [0xbe11] + list(range(10)))

    def test_incompatible_refinement(self):
        @njit
        def udt():
            try:
                lst = typed.List()
                print("A")
                lst.append(0)
                print("B")
                lst.append("fda") # invalid type will cause typing error
                print("C")
                return lst
            except Exception:
                print("D")

        with self.assertRaises(TypingError) as raises:
            udt()
        self.assertRegexpMatches(
            str(raises.exception),
            r"Cannot refine type|cannot safely cast unicode_type to int(32|64)"
        )


class TestTryExceptOtherControlFlow(TestCase):
    def test_yield(self):
        @njit
        def udt(n, x):
            for i in range(n):
                try:
                    if i == x:
                        raise ValueError
                    yield i
                except Exception:
                    return

        self.assertEqual(list(udt(10, 5)), list(range(5)))
        self.assertEqual(list(udt(10, 10)), list(range(10)))

    @expected_failure_py311
    def test_objmode(self):
        @njit
        def udt():
            try:
                with objmode():
                    print(object())
            except Exception:
                return

        with self.assertRaises(CompilerError) as raises:
            udt()
        msg = ("unsupported control flow: with-context contains branches "
               "(i.e. break/return/raise) that can leave the block ")
        self.assertIn(
            msg,
            str(raises.exception),
        )

    @expected_failure_py311
    def test_objmode_output_type(self):
        def bar(x):
            return np.asarray(list(reversed(x.tolist())))

        @njit
        def test_objmode():
            x = np.arange(5)
            y = np.zeros_like(x)
            try:
                with objmode(y='intp[:]'):  # annotate return type
                    # this region is executed by object-mode.
                    y += bar(x)
            except Exception:
                pass
            return y

        with self.assertRaises(CompilerError) as raises:
            test_objmode()
        msg = ("unsupported control flow: with-context contains branches "
               "(i.e. break/return/raise) that can leave the block ")
        self.assertIn(
            msg,
            str(raises.exception),
        )

    @unittest.skipIf(PYVERSION < (3, 9), "Python 3.9+ only")
    def test_reraise_opcode_unreachable(self):
        # The opcode RERAISE was added in python 3.9, there should be no
        # supported way to actually reach it. This test just checks that an
        # exception is present to deal with if it is reached in a case known
        # to produce this opcode.
        def pyfunc():
            try:
                raise Exception
            except Exception:
                raise ValueError("ERROR")
        for inst in dis.get_instructions(pyfunc):
            if inst.opname == 'RERAISE':
                break
        else:
            self.fail("expected RERAISE opcode not found")
        func_ir = ir_utils.get_ir_of_code({}, pyfunc.__code__)
        found = False
        for lbl, blk in func_ir.blocks.items():
            for stmt in blk.find_insts(ir.StaticRaise):
                # don't worry about guarding this strongly, if the exec_args[0]
                # is a string it'll either be "ERROR" or the guard message
                # saying unreachable has been reached
                msg = "Unreachable condition reached (op code RERAISE executed)"
                if stmt.exc_args and msg in stmt.exc_args[0]:
                    found = True
        if not found:
            self.fail("expected RERAISE unreachable message not found")


@skip_parfors_unsupported
class TestTryExceptParfors(TestCase):

    def test_try_in_prange_reduction(self):
        # The try-except is transformed basically into chains of if-else
        def udt(n):
            c = 0
            for i in prange(n):
                try:
                    c += 1
                except Exception:
                    c += 1
            return c

        args = [10]
        expect = udt(*args)
        self.assertEqual(njit(parallel=False)(udt)(*args), expect)
        self.assertEqual(njit(parallel=True)(udt)(*args), expect)

    def test_try_outside_prange_reduction(self):
        # The try-except is transformed basically into chains of if-else
        def udt(n):
            c = 0
            try:
                for i in prange(n):
                    c += 1
            except Exception:
                return 0xdead
            else:
                return c

        args = [10]
        expect = udt(*args)
        self.assertEqual(njit(parallel=False)(udt)(*args), expect)
        # Parfors transformation didn't happen
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter('always', NumbaPerformanceWarning)
            self.assertEqual(njit(parallel=True)(udt)(*args), expect)
        self.assertEqual(len(w), 1)
        self.assertIn("no transformation for parallel execution was possible",
                      str(w[0]))

    def test_try_in_prange_map(self):
        def udt(arr, x):
            out = arr.copy()
            for i in prange(arr.size):
                try:
                    if i == x:
                        raise ValueError
                    out[i] = arr[i] + i
                except Exception:
                    out[i] = -1
            return out

        args = [np.arange(10), 6]
        expect = udt(*args)
        self.assertPreciseEqual(njit(parallel=False)(udt)(*args), expect)
        self.assertPreciseEqual(njit(parallel=True)(udt)(*args), expect)

    def test_try_outside_prange_map(self):
        def udt(arr, x):
            out = arr.copy()
            try:
                for i in prange(arr.size):
                    if i == x:
                        raise ValueError
                    out[i] = arr[i] + i
            except Exception:
                out[i] = -1
            return out

        args = [np.arange(10), 6]
        expect = udt(*args)
        self.assertPreciseEqual(njit(parallel=False)(udt)(*args), expect)
        self.assertPreciseEqual(njit(parallel=True)(udt)(*args), expect)


if __name__ == '__main__':
    unittest.main()