C# 识别处理程序 Catch 块中的异常类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1802597/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 20:58:59  来源:igfitidea点击:

Identifying Exception Type in a handler Catch Block

c#exception

提问by Tomas

I have created custom exception class

我创建了自定义异常类

public class Web2PDFException : Exception
{
    public Web2PDFException(string message, Exception innerException)
        : base(message, innerException) { ... }
}

In my application how can I find out if it is my custom exception or not?

在我的应用程序中,如何确定它是否是我的自定义异常?

try {  ...  }

catch (Exception err)
{
//Find exception type here
}

采纳答案by Ruben Bartelink

UPDATED: assuming C# 6, the chances are that your case can be expressed as an exception filter. This is the ideal approach from a performance perspective assuming your requirement can be expressed in terms of it, e.g.:

更新:假设C# 6,您的情况很可能可以表示为异常过滤器。从性能角度来看,这是理想的方法,假设您的需求可以用它来表达,例如:

try
{
}
catch ( Web2PDFException ex ) when ( ex.Code == 52 )
{
}


Assuming C# < 6, the most efficient is to catch a specific Exceptiontype and do handling based on that. Any catch-all handling can be done separately

假设 C# < 6,最有效的是捕获特定Exception类型并基于该类型进行处理。任何包罗万象的处理都可以单独完成

try
{
}
catch ( Web2PDFException ex )
{
}

or

或者

try
{
}
catch ( Web2PDFException ex )
{
}
catch ( Exception ex )
{
}

or (if you need to write a general handler - which is generally a bad idea, but if you're sure it's best for you, you're sure):

或者(如果您需要编写一个通用处理程序 - 这通常是一个坏主意,但如果您确定它最适合您,那么您确定):

 if( err is Web2PDFException)
 {
 }

or (in certain cases if you need to do some more complex type hierarchy stuff that cant be expressed with is)

或(在某些情况下,如果您需要做一些无法用 表示的更复杂的类型层次结构is

 if( err.GetType().IsAssignableFrom(typeof(Web2PDFException)))
 {
 }

or switch to VB.NET or F# and use isor Type.IsAssignableFromin Exception Filters

或切换到 VB.NET 或 F# 并在异常过滤器中使用isType.IsAssignableFrom

回答by batwad

try
{
    // Some code
}
catch (Web2PDFException ex)
{
    // It's your special exception
}
catch (Exception ex)
{
    // Any other exception here
}

回答by Maximilian Mayerl

You should always catch exceptions as concrete as possible, so you should use

您应该始终尽可能具体地捕获异常,因此您应该使用

try
{
    //code
}
catch (Web2PDFException ex)
{
    //Handle the exception here
}

You chould of course use something like this if you insist:

如果你坚持,你当然可以使用这样的东西:

try
{
}
catch (Exception err)
{
    if (err is Web2PDFException)
    {
        //Code
    }
}

回答by erikkallen

try
{
}
catch (Exception err)
{
    if (err is Web2PDFException)
        DoWhatever();
}

but there is probably a better way of doing whatever it is you want.

但可能有更好的方法来做任何你想做的事。

回答by fealin

you can add some extra information to your exception in your class and then when you catch the exception you can control your custom information to identify your exception

你可以在你的类中为你的异常添加一些额外的信息,然后当你捕捉到异常时,你可以控制你的自定义信息来识别你的异常

this.Data["mykey"]="keyvalue"; //you can add any type of data if you want 

and then you can get your value

然后你就可以得到你的价值

string mystr = (string) err.Data["mykey"];

like that for more information: http://msdn.microsoft.com/en-us/library/system.exception.data.aspx

像这样了解更多信息:http: //msdn.microsoft.com/en-us/library/system.exception.data.aspx

回答by Oskuro

When dealing with situations where I don't exactly know what type of exception might come out of a method, a little "trick" I like to do is to recover the Exception's class name and add it to the error log so there is more information.

在处理我不完全知道方法可能会产生什么类型的异常的情况时,我喜欢做的一个小“技巧”​​是恢复异常的类名并将其添加到错误日志中,以便有更多信息.

try
{
   <code>

} catch ( Exception caughtEx )
{
   throw new Exception("Unknown Exception Thrown: "
                       + "\n  Type:    " + caughtEx.GetType().Name
                       + "\n  Message: " + caughtEx.Message);
}

I do vouch for always handling Exceptions types individually, but the extra bit of info can be helpful, specially when dealing with code from people who love to capture catch-all generic types.

我保证始终单独处理 Exceptions 类型,但额外的信息可能会有所帮助,特别是在处理来自喜欢捕获所有泛型类型的人的代码时。

回答by Joe B

Alternatively:

或者:

var exception = err as Web2PDFException; 

if ( excecption != null ) 
{ 
     Web2PDFException wex = exception; 
     .... 
}

回答by ΩmegaMan

Alternative Solution

替代方案

Instead halting a debug session to add some throw-away statements to then recompile and restart, why not just use the debugger to answer that questionimmediately when a breakpoint is hit?

与其停止调试会话以添加一些丢弃语句,然后重新编译和重新启动,为什么不在遇到断点时立即使用调试器来回答该问题

That can be done by opening up the Immediate Windowof the debugger and typing a GetTypeoff of the exception and hitting Enter. The immediate window also allows one to interrogate variables as needed.

这可以通过打开Immediate Window调试器的 并键入GetType关闭异常并点击 来完成Enter即时窗口还允许根据需要查询变量。

See VS Docs: Immediate Window

请参阅 VS 文档:立即窗口



For example I needed to know what the exception was and just extracted the Nameproperty of GetTypeas such without having to recompile:

例如,我需要知道异常是什么,只需提取这样的Name属性GetType而无需重新编译:

enter image description here

在此处输入图片说明