关于C#:正确的try catch语法?


Correct try-catch syntax?

本问题已经有最佳答案,请猛点这里访问。

如果我想保留堆栈跟踪,并且我有这个catch块…

1
2
3
4
5
6
7
8
9
10
11
12
try
{
    //Cause exception here...
}
catch (CustomException customEx)
{
    //Handle custom exception here...
}
catch
{
    throw;
}

上面的catch(不带参数)是否会重新引发异常?


你的问题不清楚。你的实际问题似乎是"一个catch(SpecificException)是否属于catch将军?",答案是"否"。

如果"例外"是指"除CustomException以外的任何其他例外",那么是的,它们将被重新拥有。

如果你还想重新传输后者,你还需要在catch(CustomException customex)中有一个throw


您可以使用try-catch-finally

A common usage of catch and finally together is to obtain and use resources in a try block, deal with exceptional circumstances in a catch block, and release the resources in the finally block.
For more information and examples on re-throwing exceptions, see try-catch and Throwing Exceptions. For more information about the finally block, see try-finally.

有关详细信息,请参阅

https://msdn.microsoft.com/en-us/library/dszsf989.aspx