-2

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

解决方案 1 - try/catch 嵌套

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;
4

2 回答 2

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;
}
于 2013-03-09T11:49:45.570 回答
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;
于 2013-03-09T11:49:13.120 回答