2009-12-15 109 views
1

有没有人知道是否可以将下面的catch语句块中的代码作为单个语句来编写代码?我一直无法想出办法,只是好奇有没有办法。c# - 将catch语句块中的2条语句合并成一个语句

重要提示:必须保留堆栈跟踪。

catch (Exception e) 
    { 
     if (e is MyCustomException) 
     { 
      // throw original exception 
      throw; 
     } 

     // create custom exception 
     MyCustomException e2 = 
      new MyCustomException(
       "An error occurred performing the calculation.", e); 
     throw e2; 
    } 
+1

我认为这与你将要得到的一样好。你可以首先捕获MyCustomException,并且只包含一个throw。这也许更标准,但仍然需要两个“逻辑块” – 2009-12-15 16:12:47

+4

是否有一个原因,你不想捕捉,然后在一个单独的catch中抛出更具体的异常(MyCustomException)?例如:catch(MyCustomException){throw} catch(Exception e){...} – Dexter 2009-12-15 16:17:35

+0

@Dexter - 原因是因为异常可能已经是MyCustomException。如果是这样,那么我不想在另一个MyCustomException中重新包装它,我只想重新抛出它,但确保保留堆栈跟踪。 – dcp 2009-12-15 16:19:56

回答

15

什么:

catch (MyCustomException) 
{ 
    throw; 
} 
catch (Exception ex) 
{ 
    throw new MyCustomException(ex); 
} 
+0

是的,这将起作用,但它仍然是2条语句(只是跨越不同的catch块)。 – dcp 2009-12-15 16:29:29

+0

这不是乞讨的问题吗? – 2009-12-15 16:36:10

+4

但是,它看起来比其他人好得多。代码长度不是你应该注意的唯一事情。 – Matthias 2009-12-15 16:36:16

2
catch (Exception e) 
{ 
    if (e is MyCustomException) throw; 

    throw new MyCustomException("An error occurred performing the calculation.", e); 
} 

我认为这是我们所简洁,因为它得到的,我想。

这立即引发MyCustomException的堆栈(这是你与throw;在你的问题完成的事情),而投掷MyCustomException包裹在执行中遇到其他类型Exception

或者,你可以这样做:

catch (Exception e) 
{ 
    throw new MyCustomException("An error occurred performing the calculation.", e); 
} 

,并在MyCustomException被抓的情况下,你将有一个MyCustomExceptione.InnerException哪里是e一个在堆栈或你的一个新的水平MyCustomException”在MyCustomException不是被捕的情况下,将有System.Exception

+0

我错了还是扔新会重置堆栈? – 2009-12-15 16:13:14

+0

'扔e;'会重置堆栈。 – antik 2009-12-15 16:13:43

+1

不,如果Exception已经是MyCustomException,那么您将双重包装它,所以最终会出现带有MyCustomException内部异常的MyCustomException。 – dcp 2009-12-15 16:14:57

0

这实际上是可能的。

然而,堆栈跟踪将包含其他条目:

public static class ExceptionHelper 
{ 
    public static void Wrap<TException>(Action action, Func<Exception, TException> exceptionCallback) 
     where TException : Exception 
    { 
     try 
     { 
      action(); 
     } 
     catch (TException) 
     { 
      throw; 
     } 
     catch (Exception ex) 
     { 
      throw exceptionCallback(ex); 
     } 
    } 
} 
//Usage: 
ExceptionHelper.Wrap(() => this.Foo(), inner => new MyCustomException("Message", inner)); 
0

将这项工作?

 catch (Exception e) 
     { 
      throw e.GetType() == typeof(MyCustomException) ? e : new MyCustomException("An error occurred performing the calculation.", e); 
     } 
+0

'抛e'不等于'扔' – Blorgbeard 2009-12-15 17:32:17

+0

好点!我不知道这是否可以用一行代码完成,尽管我不知道为什么会这么做,除非它是一个学术问题而不是实际要求。 – TabbyCool 2009-12-16 10:20:04