github.com/gagliardetto/golang-go@v0.0.0-20201020153340-53909ea70814/cmd/compile/internal/gc/testdata/divbyzero_test.go (about)

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