github.com/slayercat/go@v0.0.0-20170428012452-c51559813f61/src/cmd/compile/internal/gc/testdata/divbyzero.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"runtime"
     6  )
     7  
     8  var failed = false
     9  
    10  func checkDivByZero(f func()) (divByZero bool) {
    11  	defer func() {
    12  		if r := recover(); r != nil {
    13  			if e, ok := r.(runtime.Error); ok && e.Error() == "runtime error: integer divide by zero" {
    14  				divByZero = true
    15  			}
    16  		}
    17  	}()
    18  	f()
    19  	return false
    20  }
    21  
    22  //go:noinline
    23  func a(i uint, s []int) int {
    24  	return s[i%uint(len(s))]
    25  }
    26  
    27  //go:noinline
    28  func b(i uint, j uint) uint {
    29  	return i / j
    30  }
    31  
    32  //go:noinline
    33  func c(i int) int {
    34  	return 7 / (i - i)
    35  }
    36  
    37  func main() {
    38  	if got := checkDivByZero(func() { b(7, 0) }); !got {
    39  		fmt.Printf("expected div by zero for b(7, 0), got no error\n")
    40  		failed = true
    41  	}
    42  	if got := checkDivByZero(func() { b(7, 7) }); got {
    43  		fmt.Printf("expected no error for b(7, 7), got div by zero\n")
    44  		failed = true
    45  	}
    46  	if got := checkDivByZero(func() { a(4, nil) }); !got {
    47  		fmt.Printf("expected div by zero for a(4, nil), got no error\n")
    48  		failed = true
    49  	}
    50  	if got := checkDivByZero(func() { c(5) }); !got {
    51  		fmt.Printf("expected div by zero for c(5), got no error\n")
    52  		failed = true
    53  	}
    54  
    55  	if failed {
    56  		panic("tests failed")
    57  	}
    58  }