有没有人知道是否可以将下面的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;
}
我认为这与你将要得到的一样好。你可以首先捕获MyCustomException,并且只包含一个throw。这也许更标准,但仍然需要两个“逻辑块” – 2009-12-15 16:12:47
是否有一个原因,你不想捕捉,然后在一个单独的catch中抛出更具体的异常(MyCustomException)?例如:catch(MyCustomException){throw} catch(Exception e){...} – Dexter 2009-12-15 16:17:35
@Dexter - 原因是因为异常可能已经是MyCustomException。如果是这样,那么我不想在另一个MyCustomException中重新包装它,我只想重新抛出它,但确保保留堆栈跟踪。 – dcp 2009-12-15 16:19:56