catch 块中的 return 语句
我见过一些开发人员在 catch 块中使用 return 语句。为什么/什么时候这是一种有用的技术?
编辑:我实际上刚刚看到正在使用 return 关键字。
I have seen some developers use the return statement in a catch block. Why/when would this be a useful technique to employ?
EDIT: I actually just saw the return keyword being used.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
返回时;被击中,执行流程跳出函数。这只能在 void 方法上完成。
编辑:如果您不想执行函数的其余部分,则可以执行此操作。例如,如果您正在执行文件 IO 并且发生读取错误,则您不想执行处理该文件中的数据的代码,因为您没有该文件。
when return; is hit, the execution flow jumps out of the function. This can only be done on void methods.
EDIT: you do this if you don't want to execute the rest of the function. For example, if you are doing file IO and a read error happens, you don't want to execute code that handles processing the data in that file since you don't have it.
如果您知道 catch 块中函数的返回值应该是什么,这将很有用。
例子:
This would be useful if you know what the return value of the function should be in the catch block.
Example:
您可能想要捕获错误,记录它并返回一个 false 值,该值指示函数是否成功。在其他情况下,您可能希望返回一些在 try 块中计算的数据
You might want to catch the error, log it and say return a value of false which indicates if the function was successful. In other situations you might want to return some data which was calculated in the try block
.Net Framework 中的某些方法在格式不正确时确实会引发异常。
一个很好的例子是
int.TryParse(object value)
如果您的值是“10s”,它会引发异常。在这种情况下,我们知道这是因为无效转换。
所以
可能是一个告诉我们字符串是否是有效整数的函数。
如果您确实使用该形式来处理此问题,请不要执行 catch (Exception ex),因为这样做会强制 .Net 在对象内序列化错误,这有点慢。
另外,重要的是要记住,即使您在 try catch 块内使用 return,它仍然会执行 finally 块。
因此,如果您的清理代码位于finally 中,请不要担心框架将确保调用它。
我的2分钱。
N。
Some method inside the .Net Framework do throw exception when it doesn't have the good format.
A good example is the
int.TryParse(object value)
if your value is "10s" it'll trow an exception. In this case we know it's because of invalid conversion.
So
Could be a function which tell us if the string is a valid interger.
If you do use that form for this matter please do not do catch (Exception ex) as doing so force the .Net to serialize the error inside the object which is kinda slow.
Also it is important to remember that even tho you use the return inside the try catch block it'll still execute the finally block.
So if your cleaup code is inside the finally don't worry the framework will make sure to call it.
My 2 cents.
N.
如果尝试失败,您还有其他选择的任何情况。
一个例子是检查
文件
是否可用于某些操作
Any situation where you have an alternative if the attempt fails.
An example could be checking if
file
is available for someoperation
有时您并不关心抛出的异常,只关心 Try 操作失败。一个例子是 TryParse 函数,其伪代码如下所示:
There are occasions when you do not care about the exception thrown, only that the Try operation failed. An example would be the TryParse functions which in pseduo code look like: