github.com/tinygo-org/tinygo@v0.31.3-0.20240404173401-90b0bf646c27/testdata/recover.go (about)

     1  package main
     2  
     3  func main() {
     4  	println("# simple recover")
     5  	recoverSimple()
     6  
     7  	println("\n# recover with result")
     8  	result := recoverWithResult()
     9  	println("result:", result)
    10  
    11  	println("\n# nested defer frame")
    12  	nestedDefer()
    13  
    14  	println("\n# nested panic: panic inside recover")
    15  	nestedPanic()
    16  
    17  	println("\n# panic inside defer")
    18  	panicInsideDefer()
    19  
    20  	println("\n# panic replace")
    21  	panicReplace()
    22  }
    23  
    24  func recoverSimple() {
    25  	defer func() {
    26  		println("recovering...")
    27  		printitf("recovered:", recover())
    28  	}()
    29  	println("running panic...")
    30  	panic("panic")
    31  }
    32  
    33  func recoverWithResult() (result int) {
    34  	defer func() {
    35  		printitf("recovered:", recover())
    36  	}()
    37  	result = 3
    38  	println("running panic...")
    39  	panic("panic")
    40  }
    41  
    42  func nestedDefer() {
    43  	defer func() {
    44  		printitf("recovered:", recover())
    45  	}()
    46  
    47  	func() {
    48  		// The defer here doesn't catch the panic using recover(), so the outer
    49  		// panic should do that.
    50  		defer func() {
    51  			println("deferred nested function")
    52  		}()
    53  		panic("panic")
    54  	}()
    55  	println("unreachable")
    56  }
    57  
    58  func nestedPanic() {
    59  	defer func() {
    60  		printitf("recovered 1:", recover())
    61  
    62  		defer func() {
    63  			printitf("recovered 2:", recover())
    64  		}()
    65  
    66  		panic("foo")
    67  	}()
    68  	panic("panic")
    69  }
    70  
    71  func panicInsideDefer() {
    72  	defer func() {
    73  		printitf("recovered:", recover())
    74  	}()
    75  	defer func() {
    76  		panic("panic")
    77  	}()
    78  }
    79  
    80  func panicReplace() {
    81  	defer func() {
    82  		printitf("recovered:", recover())
    83  	}()
    84  	defer func() {
    85  		println("panic 2")
    86  		panic("panic 2")
    87  	}()
    88  	println("panic 1")
    89  	panic("panic 1")
    90  }
    91  
    92  func printitf(msg string, itf interface{}) {
    93  	switch itf := itf.(type) {
    94  	case string:
    95  		println(msg, itf)
    96  	default:
    97  		println(msg, itf)
    98  	}
    99  }