我在上一个问题中发布了一个代码示例,这是关键部分:
Try
first = _string.IndexOf(_firstchar) + 1
second = _string.IndexOf(_secondchar)
If first >= 1 And second >= 0 Then
retval = _string.Substring(first, second - first)
End If
Catch ex As Exception
End Try
Run Code Online (Sandbox Code Playgroud)
一位经验丰富的VB用户表示,Try/Catch的这种使用是"邪恶的".
为什么这样的用法是"邪恶的",当我们不想打扰错误时,什么是最小程度上让程序继续?
空Catch块是邪恶的,因为它可以隐藏您应该处理的异常.这里Try-Catch是多余的,你应该使用带有第二个起始索引的重载:
first = _string.IndexOf(_firstchar)
If first >= 0 Then
first += 1
second = _string.IndexOf(_secondchar, first)
If second >= 0 Then
retval = _string.Substring(first, second - first)
End If
End If
Run Code Online (Sandbox Code Playgroud)
请注意,您应该使用AndAlso而不是And.