I've never thought of anything like this, so I got curious and did a little scratch pad implementation. First off, the following works:
public class WebFaultException : Exception
{
public WebFaultException() { }
public WebFaultException(string message) : base(message) { }
public WebFaultException(string message, Exception innerException) : base(message, innerException) { }
protected WebFaultException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { }
}
public class WebFaultException<T> : WebFaultException
{
public WebFaultException() { }
public WebFaultException(string message) : base(message) { }
public WebFaultException(string message, Exception innerException) : base(message, innerException) { }
protected WebFaultException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) {}
}
As your exception definitions and then these tests both pass:
[TestMethod]
public void SpecificGeneric()
{
bool hitException = false;
try
{
throw new WebFaultException<string>();
}
catch(WebFaultException<string> e)
{
hitException = true;
}
Assert.IsTrue(hitException);
}
[TestMethod]
public void AnyGeneric()
{
bool hitException = false;
try
{
throw new WebFaultException<int>();
}
catch (WebFaultException<string> e)
{
hitException = false;
}
catch (WebFaultException e)
{
hitException = true;
}
Assert.IsTrue(hitException);
}
In terms of doing what you want specifically, there's a catch. In the code as you presented it, WebDefaultException<T>
is meaningless because you have provided no T. However, you can get around that (somewhat awkwardly) like this (another passing unit test):
[TestMethod]
public void CallingGenericMethod()
{
Assert.IsTrue(GenericExceptionMethod<int>());
}
private bool GenericExceptionMethod<T>()
{
bool hitException = false;
try
{
throw new WebFaultException<int>();
}
catch (WebFaultException<string> e)
{
hitException = false;
}
catch (WebFaultException<T> e)
{
hitException = true;
}
return hitException;
}
That is, if the method (or class) in which you're handling the exception has a generic parameter, you can actually catch WebFaultException<T>
. However, I would urge a word of caution that this is a very weird thing to do -- as a client of your method, I'm forced to pass in a type that will be used for nothing that I care about and is an internal implementation detail to you for some exception that you want to catch.
So, I'd say yes, possible. But also awkward at best and perhaps ill-advised.
WebFaultException<T>
have a base class? – leppie Jan 27 '12 at 7:02WebFaultException<T>
anywhere ... – bitbonk Jan 27 '12 at 8:30