duanhuau567787 2015-03-11 02:45
浏览 134
已采纳

使用Golang中的类型断言检测值超出范围的错误

Given the following code:

iv, err := strconv.ParseInt("18446744073709551448", 10, 64)
fmt.Println(iv)
fmt.Printf("%#v
", err)
fmt.Printf("%v
", err)

//Output:
9223372036854775807
&strconv.NumError{Func:"ParseInt", Num:"18446744073709551448", Err:(*errors.errorString)(0x1040a040)}
strconv.ParseInt: parsing "18446744073709551448": value out of range

How can I detect that the function failed due to being out of range of an int64? The strconv.ParseInt function returns an error type, but in this case it is actually a strconv.NumError type as indicated by %#v. The Error Handling and Go article mentions you can use type assertion to check for specific types of errors, but it doesn't give any examples. What expression should I use to complete this code:

if expression {
    uv, err := strconv.ParseUint("18446744073709551448", 10, 64)
}
  • 写回答

2条回答 默认 最新

  • dongya5893 2015-03-11 03:33
    关注

    We have,

    Package strconv

    var ErrRange = errors.New("value out of range")

    ErrRange indicates that a value is out of range for the target type.

    type NumError struct {
            Func string // the failing function (ParseBool, ParseInt, ParseUint, ParseFloat)
            Num  string // the input
            Err  error  // the reason the conversion failed (ErrRange, ErrSyntax)
    }
    

    A NumError records a failed conversion.

    func (e *NumError) Error() string
    

    For example,

    package main
    
    import (
        "fmt"
        "strconv"
    )
    
    func main() {
        iv, err := strconv.ParseInt("18446744073709551448", 10, 64)
        if err != nil {
            if numError, ok := err.(*strconv.NumError); ok {
                if numError.Err == strconv.ErrRange {
                    fmt.Println("Detected", numError.Num, "as a", strconv.ErrRange)
                    return
                }
            }
            fmt.Println(err)
            return
        }
        fmt.Println(iv)
    }
    

    Output:

    Detected 18446744073709551448 as a value out of range
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法