【发布时间】:2011-02-20 13:16:08
【问题描述】:
如果我不想创建自定义异常,那么捕获时如何区分它们?
if (somethingIsWrong)
throw new Exception("Something is wrong.");
else if (anotherthingIsWrong)
throw new Exception("Anotherthing is wrong.");
else
throw Exception("Nothing is wrong!");
// Now when catching them:
catch (Exception ex)
{
if (ex.Message.Contains("Something"))
ShowUserErrorThatSomethinIsWrong();
else if (ex.Message.Contains("Another"))
ShowUserErrorThatAnotherthinIsWrong();
// ...
}
我希望 System.Exception 有一个 ErrorNumber 属性来自定义异常:
if (somethingIsWrong)
throw new Exception(1001, "Something is wrong.");
// And catching them this way:
if (ex.ErrorNumber = 1001)
// ...
我知道可以从System.Exception 扩展MyExceptionClass,但有没有更好的解决方案?
这与我的另一个问题有关,您可以找到 here。
【问题讨论】:
-
为什么不想创建自定义异常?
-
知道为什么你不想创建显式异常类会很有趣——因为它们是 .NET 的方式,并且会为你提供高效和分层的错误捕获/过滤。 . 当然,错误编号有助于指向文档,但维护起来很麻烦。
标签: c# exception exception-handling try-catch