How does Go handle division by zero?

In Go, division by zero is handled differently depending on whether you are performing integer division or floating-point division.

Integer Division by Zero

If you attempt to divide an integer by zero, Go will panic at runtime. This means that the program will terminate with an error message indicating that a division by zero occurred.

Example:

package main

import "fmt"

func main() {
    a := 10
    b := 0
    result := a / b // This will cause a panic
    fmt.Println(result)
}

Output:

panic: runtime error: integer divide by zero

Floating-Point Division by Zero

For floating-point division, Go handles division by zero differently. If you divide a floating-point number by zero, the result will be +Inf (positive infinity) or -Inf (negative infinity) depending on the sign of the numerator. If you divide zero by zero, the result will be NaN (not a number).

Example:

package main

import "fmt"

func main() {
    a := 10.0
    b := 0.0
    result := a / b // This will result in +Inf
    fmt.Println(result) // Output: +Inf

    c := 0.0
    resultNaN := c / b // This will result in NaN
    fmt.Println(resultNaN) // Output: NaN
}

Summary

  • Integer Division by Zero: Causes a panic and terminates the program.
  • Floating-Point Division by Zero: Results in +Inf, -Inf, or NaN without causing a panic.

It's important to handle potential division by zero cases in your code to avoid unexpected panics.

0 Comments

no data
Be the first to share your comment!