多个try-catch还是一个? [英] Multiple try-catch or one?

查看:332
本文介绍了多个try-catch还是一个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,我会这样做:

  try 
{
code

代码,可能会抛出一个预期的异常,你想要处理

代码

代码,可能会抛出一个预期的异常你想要处理

代码
}
catch
{

}

这样做有什么好处吗?

 代码

try
{
可能会抛出您想要处理的预期异常的代码
}
catch
{
}

代码

尝试
{
代码,可能会抛出您想要处理的预期异常
}
catch
{
}

代码

更新:



我最初问这个问题,参考C#,但正如A. Levy所说,它可以应用于任何异常处理语言,所以我使标签反映出来。

解决方案

这取决于如果要为特定错误提供特殊处理,请使用多个catch块:

  try 
{
//引发异常的代码
//这行不会执行
}
catch(StackOverflowException ex)
{
/ / StackOverflowException的特殊处理
}
catch(Exception ex)
{
//所有其​​他
}
pre>

但是,如果意图是处理异常并继续执行,请将代码放在单独的try-catch块中:

  try 
{
//引发异常的代码

}
catch(Exception ex)
{
// handle
}

try
{
//此代码将执行,除非以前的catch块
//抛出异常(重新抛出或新异常)
}
catch(Exception ex)
{
// handle
}


Normally, I'd do this:

try
{
    code

    code that might throw an anticipated exception you want to handle

    code

    code that might throw an anticipated exception you want to handle

    code
}
catch 
{

}

Are there any benefits to doing it this way?

code

try
{
    code that might throw an anticipated exception you want to handle
}
catch
{
}

code

try
{
    code that might throw an anticipated exception you want to handle
}
catch
{
}

code

Update:

I originally asked this question w/reference to C#, but as A. Levy commented, it could apply to any exception handling language, so I made the tags reflect that.

解决方案

It depends. If you want to provide special handling for specific errors then use multiple catch blocks:

try
{ 
    // code that throws an exception
    // this line won't execute
}
catch (StackOverflowException ex)
{
    // special handling for StackOverflowException 
}
catch (Exception ex)
{
   // all others
}

If, however, the intent is to handle an exception and continue executing, place the code in separate try-catch blocks:

try
{ 
    // code that throws an exception

}
catch (Exception ex)
{
   // handle
}

try
{ 
    // this code will execute unless the previous catch block 
    // throws an exception (re-throw or new exception) 
}
catch (Exception ex)
{
   // handle
}

这篇关于多个try-catch还是一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆