# 如何优雅的在 Go 语言中处理被除数为零？

### 题目来源及自己的思路

``````package main

import "fmt"

func main() {
fmt.Println(1 / 0)
}
``````

``````package main

import "fmt"

func main() {
foo := -0.0
fmt.Println(1.0 / foo)
}``````

4 个回答

``````// To gracefully handle division by zero in Go, we can use a defer statement to recover from a runtime panic that occurs when dividing by zero.
// Here is an example:

func divide(a, b int) (result int, err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("runtime error: %v", r)
}
}()
result = a / b
return result, nil
}

// In the above code, we use a defer statement to recover from a runtime panic that occurs when dividing by zero.
// The recover function returns the value passed to the panic function, which in this case is the runtime error message.
// We then use the fmt.Errorf function to create a new error object with the error message.
// Finally, we return the error object along with the result of the division.``````

``````type ZeroDivisionError struct {
message string
}

func (e *ZeroDivisionError) Error() string {
return e.message
}

func divide(dividend, divisor float64) (float64, error) {
if divisor == 0 {
return 0, &ZeroDivisionError{"division by zero"}
}
return dividend / divisor, nil
}
``````

``````result, err := divide(10.0, 2.0)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(result)
}
``````

go 本身就是个流程化的处理语言；执行前检查下被除数就是了。

``````if b == 0 {
return fmt.Errorf("除数不能 为 0")
}

fmt.Println(a/b)``````

###### 你尚未登录，登录后可以
• 和开发者交流问题的细节
• 关注并接收问题和回答的更新提醒
• 参与内容的编辑和改进，让解决方法与时俱进