尝试/捕捉并返回

时间:2013-03-09 11:45:02

标签: language-agnostic

您更喜欢什么样的解决方案? 我更喜欢解决方案2,但我想知道是否存在更好的做法 谢谢大家

解决方案1 ​​ - 尝试/捕获嵌套

try
{
   //some code that could throws Exception1
   try
   {
        //some code that could throws Exception2
        return success;
   }      
   catch (Exception2 e)
   {
      return failure;
   }
}
catch (Exception1 e)
{
  return failure;
}    

解决方案2 - 尝试/捕捉顺序

try
{
   //some code that could throws Exception1 
}
catch (Exception1 e)
{
  return failure;
}

try
{
    //some code that could throws Exception2
}      
catch (Exception2 e)
{
  return failure;
}

return success;

2 个答案:

答案 0 :(得分:1)

-4!我认为这是一个合理的问题,特别是刚开始的人。 为什么这是一个糟糕的问题?

我个人会使用下面的代码,除非有令人信服的理由不这样做。

try
{
   //some code that could throws Exception1 
   //some code that could throws Exception2
   //some code that could throws Exception3
}
catch (Exception e)
{
  return failure;
}

答案 1 :(得分:0)

你可以尝试

try
{
   //some code that could throws Exception1 
   //some code that could throws Exception2
}
catch (Exception1 e)
{
   return failure;
}
catch (Exception2 e)
{
   return failure;
}

return success;