I have created custom exception class
public class Web2PDFException : Exception
{
public Web2PDFException(string message, Exception innerException)
: base(messag开发者_C百科e, 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
}
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.
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.:
try
{
}
catch ( Web2PDFException ex ) when ( ex.Code == 52 )
{
}
Assuming C# < 6, the most efficient is to catch a specific Exception
type and do handling based on that. Any catch-all handling can be done separately
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
)
if( err.GetType().IsAssignableFrom(typeof(Web2PDFException)))
{
}
or switch to VB.NET or F# and use is
or Type.IsAssignableFrom
in Exception Filters
精彩评论