C# 如何捕获System.Exception的不同扩展并确定抛出了哪个扩展?
我要做的看起来像C# 如何捕获System.Exception的不同扩展并确定抛出了哪个扩展?,c#,exception,exception-handling,C#,Exception,Exception Handling,我要做的看起来像 catch ( Exception e ) { Type etype = e.GetType(); if (etype == ArgumentException.GetType()) { Console.WriteLine("Invalid Arguments: {0}", e.Message); }
catch ( Exception e )
{
Type etype = e.GetType();
if (etype == ArgumentException.GetType())
{
Console.WriteLine("Invalid Arguments: {0}", e.Message);
}
else if (etype == ArgumentOutOfRangeException.GetType())
{
Console.WriteLine("Arguments Out of Range: {0}", e.Message);
}
// ...
}
我得到了错误
非静态字段、方法或对象需要对象引用
属性“System.Exception.GetType()”
在我的上下文中,这个错误意味着什么?我的方法的根本缺陷是什么 对于预期的异常类型,只需使用单独的
catch
块即可:
try
{
// do something
}
catch (ArgumentException e)
{
// respond to an ArgumentException
}
catch (ArgumentOutOfRangeException e)
{
// respond to an ArgumentOutOfRangeException
}
// ...
你不能那样做
GetType仅用于实例化的异常对象
你应该使用
catch (ArgumentOutOfRangeException e)
{
[...]
}
catch (ArgumentException e)
{
[...]
}
您应该始终按照从具体到具体的顺序执行捕获操作。您可以执行以下操作:
try {
...
}
catch (ArgumentOutOfRangeException e)
{
Console.WriteLine("Arguments Out of Range: {0}", e.Message);
}
catch (ArgumentException e)
{
Console.WriteLine("Invalid Arguments: {0}", e.Message);
}
在C#6.0中,您可以根据设置的条件进一步指定要捕获哪些异常。例如:
// This will catch the exception only if the condition is true.
catch (ArgumentException e) when (e.ParamName == "myParam")
{
Console.WriteLine("Invalid Arguments: {0}", e.Message);
}
你只是:
catch ( ArgumentException e )
{
// Handle ArgumentException
}
catch ( ArgumentOutOfRangeException e )
{
// Handle ArgumentOutOfRangeException
}
catch ( Exception e )
{
// Handle any other exception
}
只能对对象实例调用
GetType()
。如果您想保持您的风格(而不是像其他答案中那样,使用单独的捕捉块):
我觉得你不是真正的唐纳德·克努斯。
catch ( Exception e )
{
Type etype = e.GetType();
if (etype == typeof(ArgumentException))
{
Console.WriteLine("Invalid Arguments: {0}", e.Message);
}
else if (etype == typeof(ArgumentOutOfRangeException))
{
Console.WriteLine("Arguments Out of Range: {0}", e.Message);
}
// ...
}