I have decided to use Exceptions in my code to pass error handling around. I found myself duplicating code each time I wanted to create a new exception. These classes were nothing special and only contained a messaged. But I have come to rely on type safety when handing them. Is there a way to provide a new exception class type without having to re-implement the constructors?
[Serializable]
class MyNewException : MyBaseException
{
public MyNewException (String tMsg)
: base(tMsg)
{
}
public MyNewException (String tMsg, Exception tInnerEx)
: base(tMsg, tInnerEx)
{
}
}
The code above is duplicated many times over for each different type of exception I want to define.
Unfortunately, no, the constructors have to be provided since they are not inherited.
In addition, unless you are catching these specific exceptions and performing explicit processing when they occur, I would recommend having a generic exception that contains the additional information that you might need. However, this may not apply in your case.
Related
I want to create an abstract class with an common exception handling pattern:
public abstract class Widget
{
public IFoo CreateFoo()
{
try
{
CreateFooUnsafe();
}
catch(Exception ex)
{
throw new WidgetException(ex, moreData, evenMoar);
}
}
protected abstract IFoo CreateFooUnsafe();
}
The intention is to have a standard exception handling pattern across all deriving objects. The abstract CreateFooUnsafe() method should not be expected to contain any exception handling. Implementations would probably a single line of return new Foo(...)
What I want to know is whether there are any standard naming conventions associated with this pattern, particularly where exception-throwing code is expected?
The names above seem somewhat appropriate, but not entirely without smell.
This appears to be an example of the template method pattern.
Template method is a pattern which can be expressed in many object-oriented languages by using a public non-virtual function to implement some over-arching behavior, and a protected virtual (or abstract) method to supple the concrete behavior in subclasses.
In your example, you are using the template method to catch all exceptions bubbling out of the inner implementation and wrapping them in a custom exception type. One comment I would make about this specific practice, is that it only makes sense if you can add contextual information that would allow calling code to better handle the exception. Otherwise, it may be better to simply allow the source exceptions to propogate out.
The short answer is no.
There is no convention in the Template Pattern to designate what type and when an exception is thrown. That kind of information is included in some section of the documentation as per MSDN. Using C# and XML comments you can easily generate such documentation.
I'm under the impression that there might be a naming convention in place for the Template Pattern itself sans any referencing to exception handling. As I understand it, naming might look like this:
public abstract class Widget
{
public void PerformAction()
{
this.PerformActionImpl();
}
protected virtual void PerformActionImpl(){}
}
Where Impl is a shorthand for "Implementation". Personally I don't like that naming style so don't use it but I'm sure I've read it somewhere semi authoritative that that is "the" way to do it.
I wouldn't use any of this in your case however as what you really to seem to want to either Factory or AbstractFactory.
..
With regard to your exception query, it seems to me the code is a little inside out tho I disagree with some of the other comments depending on your circumstances.
Wrap and throw is an entirely valid exception handling technique.
The additional context provided by the type of the exception itself may well be enough to route the exception to an appropriate handler. i.e. you've transformed an Exception into a WidgetException which one would expect then has context within your application. So that might well be good enough.
Where you've done the wrapping I do however disagree with.
I would do the catching wrapping and throwing from within the subclass implementation of the virtual method as only that subclass is going to have enough understanding of what it's doing to know whether the Exception is indeed a WidgetException and therefore wrap and throw or something a little more hairy that should propagate.
The code as it stands is making some massive assumptions about the cause of the exception and in that sense rendering any use of a custom exception next to useless. i.e. everything is now a WidgetException.
So while I believe type alone could be enough to contextualise the exception I dont believe the code is making that decision in the right place. I understand the motivation behind the implementation you've chosen as it seems like a really tasty shortcut, "the myth of the all knowing base class" but the mere fact that you declared it as abstract should provide a significant clue that the class is intended to be ignorant by design.
So with respect to the crosscutting concern of exception handling I don't think you should looking so much for a pattern to make your life easier but rather a framework to abstract all the guff away.
For example the Enterprise Library.
There are several different patterns swimming about in the code above. Among other things, it looks a bit like the Abstract Factory pattern, i.e., you've got an abstract class which is implementing a factory method that returns concrete objects which implement a specific interface.
As to whether this sort of exception handling is a good idea or not -- I would tend to agree with the other folks, that I can't typically see a lot of value in this approach. I see what you're trying to do, namely, provide a single sort of exception to handle, much as the CreateFoo() returns a single interface (IFoo). But the only benefit I can think of to that approach is if you provide some interesting and relevant troubleshooting information in the WidgetException (e.g., some database or service connection strings, or some special processing logic around the stack trace). If you're just wrapping the original exception so that your clients can deal with a WidgetException, you haven't really accomplished much: they could just as easily deal with the base Exception type.
In .net, c#
There are many sub-classes of Exception already existing,
what are they and when do we use them instead of creating our own sub-class?
This question is duplicate of c# is there an exception overview
The link provided by Jason is pretty comprehensive, but a lot of the exception types in it (such as NullReferenceException or IndexOutOfRangeException) are really only ever thrown by the framework; it would not be very appropriate for you was a developer to explicitly throw them.
Here are, in my opinion, a handful of the most useful exception types for a developer.
ArgumentNullException
This one's obvious: one of the arguments passed to a method was null, but for this particular method, a null value for that argument is not allowed.
ArgumentOutOfRangeException
A value was supplied to a method that is outside of the range that makes sense for that method.
Example
In most methods that take a parameter representing a magnitude or length, only positive values make sense for that parameter. So a check such as
if (x < 1)
{
throw new ArgumentOutOfRangeException("x");
}
is common.
FormatException
This is a pretty reasonable choice when you're writing your own custom text-parsing method, or really any code that expects strings to match a certain format, and some input is supplied that the code can't understand.
InvalidOperationException
I tend to use this one a lot (probably overuse it, actually) whenever I'm not sure what else to use. Generally I think of this type as conveying that the client attempted to do something illegal, for reasons relevant to the current class or method.
Example
Many IEnumerator<T> implementations throw an InvalidOperationException when the collection they're enumerating is modified. This is a reasonable design choice, as it is much easier to design a collection class that does not handle this case than it is to design one that does.
NotSupportedException
This one typically makes sense in a class that derives from some base class and only offers a partial implementation of that base class's abstract members.
Example
Some developers choose to write base classes with "optional" functionality that may be provided by derived classes or may not be. Below is an example:
abstract class Animal : Organism
{
public virtual bool EatsPlants
{
get { return false; }
}
public virtual void EatPlant(Plant food)
{
throw new NotSupportedException();
}
public virtual bool EatsAnimals
{
get { return false; }
}
public virtual void EatAnimal(Animal food)
{
throw new NotSupportedException();
}
}
class Herbivore : Animal
{
public override bool EatsPlants
{
get { return true; }
}
public override void EatPlant(Plant food)
{
// whatever
}
}
Obviously this is just my own personal (and subjective) list; but I thought it might give you an idea of what kinds of exceptions you can and should be leveraging within your own code.
Here is list of common exception types. If you want to know when to create your own exceptions, then try:
What are some best practices for creating my own custom exception?
For a list of sub-classes of Exception I recommend that you use the .NET Reflector.
http://www.red-gate.com/products/reflector/
I'm looking at creating a helper method to set an exception's message, automatically setting String.Format, adding in inner exceptions, setting commandline exit codes, etc; something like:
public static void MyExceptionHelper(ExitCode code, string message) {}
public static void MyExceptionHelper(ExitCode code, Exception e) {}
public static void MyExceptionHelper(ExitCode code, Exception e, String message) {}
public static void MyExceptionHelper(ExitCode code, Exception e, String message, params object[] args) {}
// etc...
The BCL has got a few static classes around that does that sort of thing (eg System.ThrowHelper in mscorlib).
Where is the best place to put these? As overloaded constructors on the exception, in a separate static class (like the BCL), as static methods on the exception itself, or somewhere else?
I'd recommend the Exception application block in EnterpriseLibrary, it has a very elegant design for dealing with exceptions and if you don't want all of EntLib I'd recommend copying their interface.
For methods like this, I prefer overloaded constructors. You're clearly using it to create a new object, and that's what a constructor is for.
Once you get into the world of static methods, it's not always clear where they should end up. You'll need to analyze who will use them and how they will be used, then examine the pros and cons of each potential location. Then, you will know where to put them.
I'd just make these constructors for your exception class.
Most of the time, the exception helpers in the BCL are there to support localization (which is usually wrapped up in the SR internal class you'll find in almost all .NET BCL assemblies.) The general idea is that you use a helper method to pass in some basic data for an exception, and the helper handles the retrieval of resources and formatting of data for you to create the exception. The benefit is that you centralize code for exceptions that may be thrown from multiple locations, but which need to be created in the same way. So generally, same idea as any other utility class or inherited object...promotes reuse and maintainability.
As for where to put them...I like to have an "internal area" in each of my assemblies with an exception helper, resource helper, and other internal "assembly support" types.
This looks like you have enough custom behavior to want to derive your own exception class, and put this behavior on it. Depending on whether or not you want to interact with the base Exception sine qua Exception later on, you might want to have these be constructors on your derived class that set the base to the passed-in exception, and do your modifications on that exception from within your class; polymorphism will allow that instance to be recast up to a base Exception for interaction from there.
while writing a custom attribute in C# i was wondering if there are any guidelines or best practices regarding exceptions in attributes.
Should the attribute check the given parameters for validity? Or is this the task of the user of the property?
In a simple test I did the exception was not thrown until i used GetCustomAttributes on a type with an exception throwing attribute.
I just think it's a bit awkward to get an exception from an Attribute only when explicitly asking for them.
Example Attribute with exception:
[AttributeUsage(AttributeTargets.Interface, AllowMultiple = false, Inherited = false)]
sealed public class MyAttribute : Attribute
{
public string SomeValue { get; private set; }
public MyAttribute(string someValue)
{
if(string.IsNullOrEmpty(someValue))
{
throw new ArgumentNullException("path");
}
if(!someOtherCheck(someValue))
{
throw MyAttributeException("An other error occured");
}
SomeValue = someValue;
}
}
Attributes are only actually constructed when you use reflection, so that's the only time you can throw an exception. I can't remember ever using an attribute and having it throw an exception though. Attributes usually provide data rather than real behaviour - I'd expect the code which uses the attribute to provide any validation. I know this isn't like normal encapsulation, but it's the way it tends to be in my experience.
With a few exceptions with compiler-sepcific meaning (such as [PrincipalPermission] etc.) attributes can't interact directly with code without being asked to. However, if you use the AOP (Aspect Oriented Programming) tool "PostSharp", your aspect attributes can add behaviour to your class. Not simple, but it's a very useful trick sometimes.
We have some reasonably complex Attributes in our project, so we include validation of inputs. For example, as part of our I18N and L10N work, we have attributes that perform resource lookups (much like the attributes in the framework that are used to localise Category and Description strings for properties in the designers). These custom attributes have to have some validation in order for them to work.
The simple attributes we have use no validation because we'd rather the consuming code failed, indicating the location of the error.
So, in conclusion, it really depends on the complexity of the attribute; if it is instantiated with one kind of data but expected to provide another (such as in resource lookups), it should contain validation, otherwise, it probably shouldn't.
In a follow-up to a previous question regarding exceptions, what are best practices for creating a custom exception in .NET?
More specifically should you inherit from System.Exception, System.ApplicationException or some other base exception?
In the C# IDE, type 'exception' and hit TAB. This will expand to get you started in writing a new exception type. There are comments withs links to some discussion of exception practices.
Personally, I'm a big fan of creating lots of small classes, at that extends to exception types. For example, in writing the Foo class, I can choose between:
throw new Exception("Bar happened in Foo");
throw new FooException("Bar happened");
throw new FooBarException();
where
class FooException : Exception
{
public FooException(string message) ...
}
and
class FooBarException : FooException
{
public FooBarException()
: base ("Bar happened")
{
}
}
I prefer the 3rd option, because I see it as being an OO solution.
Inherit from System.Exception. System.ApplicationException is useless and the design guidelines say "Do not throw or derive from System.ApplicationException."
See http://blogs.msdn.com/kcwalina/archive/2006/06/23/644822.aspx
There is a code snippet for it. Use that. Plus, check your code analysis afterwards; the snippet leaves out one of the constructors you should implement.
I think the single most important thing to remember when dealing with exceptions at any level (making custom, throwing, catching) is that exceptions are only for exceptional conditions.
The base exception from where all other exceptions inherit from is System.Exception, and that is what you should inherit, unless of course you have a use for things like, say, default messages of a more specific exception.