捕获、处理然后重新抛出异常?
今天我遇到了一个有趣的困境。 我有一个函数可以处理信息并检查重复值,然后返回下一个不重复的数字。 所以,我有这样的东西:
Public Function GetNextNonDuplicateNumber(NumberToCheck as Long) as Long
//the non-duplicate the function will return
Dim NonDuplicate as Long
If CheckForDuplicate(NumberToCheck) = True Then
Throw New DuplicateException()
Else
NonDuplicate = NumberToCheck
End If
End Function
然后在函数的底部,我有一个 catch 块,它通过递增来处理重复项,直到不再有重复项,如下所示:
Catch ex as DuplicateException
NonDuplicate = IncrementToNonDuplicateValue(NumberToCheck)
Throw ex
Return NonDuplicate
End Function
如您所见,我想处理特别是异常,但我也想在完成后抛出它,因为我想提醒函数外部的其他代码。
问题是,简单地抛出它就会以 null
值退出函数。 我是否以错误的方式思考try/catch
,或者有没有办法解决这个问题?
I ran into an interesting dilemma today. I have a function that handles information and checks for duplicate values, then returns the next number that is not a duplicate. So, I have something like this:
Public Function GetNextNonDuplicateNumber(NumberToCheck as Long) as Long
//the non-duplicate the function will return
Dim NonDuplicate as Long
If CheckForDuplicate(NumberToCheck) = True Then
Throw New DuplicateException()
Else
NonDuplicate = NumberToCheck
End If
End Function
Then at the bottom of the function I have a catch block that handles the duplicate by incrementing until I don't have a duplicate any more, like this:
Catch ex as DuplicateException
NonDuplicate = IncrementToNonDuplicateValue(NumberToCheck)
Throw ex
Return NonDuplicate
End Function
As you can see, I want to handle the exception specifically, but I also want to throw it when I'm done because I want to alert other code outside the function.
The problem is that simply throwing it exits out of the function with a null
value. Am I thinking about a try/catch
the wrong way, or is there a way around this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您捕获了异常并从中恢复(使用 IncrementToNonDuplicate...),那么就没有理由再抛出异常了。 catch 和 end try 之间的代码应该只清理资源,例如关闭文件或数据读取器(如果您要重新抛出它)。
您宁愿返回一个包含 NonDuplicate 值和有关函数中错误的所需信息的结构。
另一种方法是抛出一个自定义异常,其中包含诸如“无效数字:它应该是......”之类的信息
If you caught an exception and recovered from it (with your IncrementToNonDuplicate...) then there is no reason to throw an exception anymore. Code between catch and end try should just clean the resources like closing a file or datareader if you will rethrow it.
You could rather return a structure that contains NonDuplicate value and required information about errors in function.
Other way would be to throw a custom exception that will contain information like "Invalid number: it should be...)
您可以返回一个布尔值来指示是否找到重复项,并更改要通过引用传入的参数,以便可以更新该值。
You can return a boolean indicating if a duplicate is found, and change the parameter to be passed in by reference so you can update the value.