douhao2548 2019-08-27 06:19
浏览 48
已采纳

如何捕获“切片边界超出范围”错误并为其编写句柄

I read other questions about the "slice bounds of range" here in the stackoverflow, but none of them using the same context from this. Then, none of the answers helped me.

In my use case, the "golang's syntax" of substring using [] doesn't return an error variable. It launches a runtime error using the "panic" instruction. My goal is to avoid to reach on the "panic" instruction. I need to treat this error and provide messages that describe with more details the context around the moment where this error had occurred.

Obs: The content of the string variable which one I need to get the substring value is totally dynamic and the indexes that I have been using to get the substring value is equally calculated dynamically.

  • 写回答

1条回答 默认 最新

  • dsjlqkbpn029473708 2019-08-27 06:23
    关注

    You need to do bounds checking on your indexes:

    if j >= 0 && j <= len(str) {
       y = str[:j]
    }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部