我想捕获异常并判断是我故意抛出错误还是其他类似运行时错误(对象不是对象实例)的错误。
try
{
throw new Exception("throw this", "these can be many possible values");
}
catch (System.Exception ex)
{
if (IThrew) // <--- how can i tell if i threw or not?
{
exReport = "one thing"; // <--- Should go in here in this example.
}
else
{
exReport = "another thing";
}
throw new FaultException<ExceptionReport>(exReport, new FaultReason(ex.Message), new FaultCode("Receiver"));
}
澄清:
我需要记录所有异常,然后在最后将它们显示在异常报告(异常数组)中。这是 schema 的一部分我必须遵守。 (所以请不要让我用另一种方式来做)。
我的一切都运行良好,输出如下:
...
<soap:Detail>
<ows:ExceptionReport>
<Exception exceptionCode="…" locator="…">
<ExceptionText>…</ExceptionText>
</Exception>
<Exception exceptionCode="…" locator="…">
<ExceptionText>…</ExceptionText>
</Exception>
</ows:ExceptionReport>
</soap:Detail>
...
问题是,当我的 ExceptionReport 中已经有一些错误时,就会发生运行时错误。
但我意识到我在这方面走错了路……正如 Gary 提到的……我不应该使用异常作为流程控制。
最佳答案
使用不同的异常(exception)。给它自己的 catch 子句。
关于c# - 我如何判断异常是否被故意抛出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9007036/