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

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

问题描述:

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.

我在stackoverflow中阅读了有关“范围的切片边界”的其他问题,但没有一个使用相同的 然后,没有答案对我有帮助。 p>

在我的用例中,使用[]的子字符串的“ golang语法”不会返回错误变量。 它使用“ panic”指令启动运行时错误。 我的目标是避免触及“ panic”指令。 我需要处理此错误,并提供描述此错误发生时上下文的详细信息。 p>

Obs: 我需要获取子字符串值的字符串变量的内容是完全动态的,并且我一直用于获取子字符串值的索引是相同的 动态计算。 p> div>

You need to do bounds checking on your indexes:

if j >= 0 && j <= len(str) {
   y = str[:j]
}