Oma*_*eji 1 c# exception-handling
我正在尝试编写一些捕获特定异常的代码,并为调用堆栈处理更高级别的内容抛出更有用的代码,同时捕获更多常规异常并处理它们.
代码是这样的:
try
{
// Do stuff
}
catch (SomeException e)
{
throw new SomeExceptionWithContextInfo();
}
catch (Exception e)
{
// Handle unexpected exception gracefully
}
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是一般的例外是捕获我的新异常.有没有办法避免这种情况?
我当前的解决方案涉及检查异常的类型,如果它的类型是我刚刚创建的类型,则再次抛出它.
您发布的代码应该有效,如此测试应用中所示:
using System;
class OtherException : Exception {}
class Test
{
static void Main(string[] args)
{
try
{
Foo();
}
catch (OtherException)
{
Console.WriteLine("Caught OtherException");
}
}
static void Foo()
{
try
{
string x = null;
int y = x.Length;
}
catch (NullReferenceException)
{
throw new OtherException();
}
catch (Exception)
{
Console.WriteLine("Caught plain Exception");
}
}
}
Run Code Online (Sandbox Code Playgroud)
这只是打印"Caught OtherException"而不是"Caught Plain Exception".您确定在实际代码中没有嵌套的try块吗?你能发一个简短但完整的例子来说明你的问题吗?
你真的需要在你的方法中捕获异常吗?这很少是一个好主意.
| 归档时间: |
|
| 查看次数: |
276 次 |
| 最近记录: |