summaryrefslogtreecommitdiff
path: root/libphobos/testsuite/libphobos.exceptions/chain.d
blob: 0305707fc62aea6cad941b58a1b9e5ba9b5f0af3 (plain)
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
// Author: Ali Çehreli
// See https://forum.dlang.org/post/o2n7f8$2p1t$1@digitalmars.com

import core.stdc.stdio;

class TestException : Exception
{
    this(string msg)
    {
        super(typeof(this).stringof~": "~msg);
    }
}

class TestError : Error
{
    this(string msg)
    {
        super(typeof(this).stringof~": "~msg);
    }
}

// Causes an exception chain where the node at index errorIndex is an
// Error (others are all Exceptions).
void causeExceptionChain(size_t chainLength, size_t errorIndex)
{
    void throws(size_t n)
    {
        scope (exit)
        {
            string msg = [ cast(char)('a'+n) ].idup;
            if (n == errorIndex)
            {
                throw new TestError(msg);
            }
            else
            {
                throw new TestException(msg);
            }
        }

        if (n != 0)
        {
            // Redundant 'return' keyword due to
            // https://issues.dlang.org/show_bug.cgi?id=16960
            return throws(n - 1);
        }
    }

    throws(chainLength - 1);
}

void main()
{
    try
    {
        // -1 would mean "no Error in the chain". Change this to a
        // number between 0 and 4 (inclusive) then you will realize
        // that the Exception below will not be caught.
        size_t errorIndex = 3;
        causeExceptionChain(5, errorIndex);
    }
    catch (Error original)
    {
        printf("Caught\n");
        string prefix = "";
        for ({ size_t i; Throwable ex = original; } ex; ex = ex.next, ++i)
        {
            printf("%.*s%.*s\n", cast(int)prefix.length, prefix.ptr, cast(int)ex.msg.length, ex.msg.ptr);
            prefix = prefix~" ";
        }
        printf("Bypassed chain was:\n");
        prefix = "";
        for ({ size_t i; Throwable ex = original.bypassedException; } ex; ex = ex.next, ++i)
        {
            printf("%.*s%.*s\n", cast(int)prefix.length, prefix.ptr, cast(int)ex.msg.length, ex.msg.ptr);
            prefix = prefix~" ";
        }
    }
}