使用Try-Catch-Finally处理算术异常
我想尝试两种不同的事情(两者都有很大的失败可能性),因此我想使用“finally”语句来运行“安全”,以防万一前两个尝试都 失败。
采取以下示例(不,这不是我在项目中使用的代码!)。
int zero = 0;
int one = 1;
try
{
// Throws ' cannot divide by zero ' error
int error = one / zero;
}
catch
{
// Throws error again of course
int somenum = one / zero;
}
finally
{
MessageBox.Show("I can never make it here ...");
}
因此,我希望我的程序执行以下操作:
- 尝试除以零
- 如果步骤#1失败,我希望“catch”语句运行其代码(在本例中应该再次失败)。
- 如果步骤 #1 和 #2 都失败,我希望我的程序在“finally”语句中显示 MessageBox。
我和这个人亲近吗?
I would like to try TWO different things (both have a strong possibility of failure) and for this reason I would like to use the "finally" statement to run a "safety" just in case the first two tries both fail.
Take the following example (no this is not the code I am using in my project!).
int zero = 0;
int one = 1;
try
{
// Throws ' cannot divide by zero ' error
int error = one / zero;
}
catch
{
// Throws error again of course
int somenum = one / zero;
}
finally
{
MessageBox.Show("I can never make it here ...");
}
So, I would like for my program to do the following:
- Attempt to divide by zero
- If step #1 fails, I would like for the 'catch' statement to run its code (which should once again fail in this example).
- IF both steps #1 and #2 fail, I would like for my program to display the MessageBox in the 'finally' statement.
Am I even close with this one?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
根据我的经验,您似乎需要在第一次捕获中再次尝试:
From my experience it seems you would need to put another try inside of your first catch:
原因是您在 catch 块上生成了异常并且没有处理它。
您可以避免放置嵌套的
try catch
块。The reason of that is because you generate an exception on the
catch
block and don`t handle it.You can avoid that placing a nested
try catch
block.在最佳实践中,您不应将可能失败的代码放在 catch 中。
对于您的示例,您应该使用嵌套的 try-catch-finally
使用 finally 部分来释放您的资源,并且当您需要在 try 或 catch 之后,您的代码将执行 100%。
Inbest practice you should not place a code in catch that possible of failure.
for you sample you should use nested try-catch-finally
use finally section for free your resource and when you want after try or catch your code will executes 100%.
你正在做的事情将会起作用。但请注意,在finally 块中显示消息后,异常将重新抛出。
What you are doing will work. but note that after the message displayed in the finally block the exception will re-throw.