How to create exception helpers? - c#

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.

Related

Exception Driven Programming C#

Although not much popular in Micro-services & Restful architecture, (I'm presuming). We prefer to raise graceful business excetion by means of custom exception classes derived from ApplicationException.
Is there any mechanism to self declare, by some compile feature that
Ex1, Ex2, Ex3 are the possible business exceptions thrown by a class service.
If you're already familiar with WCF, hope you have got it. I'm Something on the lines of WCF
(Exception contract)
Example:
public class BlobChecksumMatchException : ApplicationException
{
public BlobChecksumMatchException(string msg) : base(msg)
{
}
}
EDIT:
(Not to mention Exception base of course can be thrown for whatsoever reason, I'm just looking out for predefining business exception classes)
There's no such built-in mechanism in C# or .NET. However, you have a couple of workaround options:
1) If that information is for human consumption, you can use XML documentation comments as pointed out by Andreas Zita.
2) If you need a machine-readable mechanism, you could declare a custom "ThrowsException" attribute and apply it to your class or methods, then retrieve these using reflection:
class MyBusinessClass
{
[ThrowsException(typeof(Ex1))]
[ThrowsException(typeof(Ex2))]
public void DoSomething() {}
}
Note however that reflection is expensive, depending on your performance requirements you might need to implement some caching mechanism for that information.

NotImplementedException -- but it's something that should never be called

Logically the methods in question should be abstract but they are on a parent form that gets inherited from and Visual Studio will have fits if they are declared abstract.
Ok, I made the bodies throw a NotImplementedException. Resharper flags that and I'm not one to tolerate a warning in the code like that.
Is there an elegant answer to this or do I have to put up with some ugliness? Currently I am doing:
protected virtual void SaveCurrentItem()
{
Trace.Assert(false, "Only the children of FormCore.SaveCurrentItem should be called");
}
protected virtual void SetItem()
{
Trace.Assert(false, "Only the children of FormCore.SetItem should be called");
}
The class itself should never be instantiated, only its children. However, Visual Studio insists on creating one when you look at the designer of one of its children.
You might consider creating a nested, protected interface. For example:
protected interface IManageItems
{
void SaveCurrentItem();
void SetItem();
}
Each class that inherits from FormCore could individually implement the interface. Then you wouldn't have the risk of calling the base class implementation because there wouldn't be any.
To call the methods from your base class:
(this as IManageItems)?.SaveCurrentItem();
This would have the effect of making the methods act as if they were virtual without having an initial declaration in the parent class. If you wanted to force a behavior that was closer to abstract, you could check to see if the interface was being implemented in the constructor of the base class and then throw an exception if it wasn't. Things are obviously getting a little wonky here, because this is essentially a workaround for something the IDE is preventing you from doing, and as such there's no real clean, standard solution for something like this. I'm sure most people would cringe at the sight of a nested protected interface, but if you don't want an implementation in your base class and you can't mark your base class abstract, you don't have a lot of options.
Another thing to consider is favoring composition over inheritance to provide the functionality that you need.
On the other hand instead of using an interface, it may be appropriate to simply throw a NotSupportedException in a circumstance where the class cannot perform the action. NotImplementedException is designed to be used for in-development projects only, which is why ReSharper is flagging the method.
NotSupportedException: The exception that is thrown when an invoked method is not supported, or when there is an attempt to read, seek, or write to a stream that does not support the invoked functionality.
One use case is:
You've inherited from an abstract class that requires that you override a number of methods. However, you're only prepared to provide an implementation for a subset of these. For the methods that you decide not to implement, you can choose to throw a NotSupportedException.
See NotSupportedException documentation on MSDN for more information and usage guidelines.
Resharper raises the warning to alert users that code has not been completed. If your actual desired behaviour is to not support those methods, you should throw a NotSupportedException instead of NotImplementedException, to make your intentions clearer.

Whether to use static class or not [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
When to Use Static Classes in C#
I will write code in which I need class which holds methods only. I thought it is good idea to make class static. Some senior programmer argue that do not use static class. I do not find any good reason why not to use static class. Can someone knows in C# language there is any harm in using static class. Can static class usage required more memory than creating object of class? I will clear that my class do not have single field and hence property too.
For further information I will explain code also.
We have product in which we need to done XML handling for chart settings. We read object from XML file in class Library which holds chart related properties. Now I have two Layers first is product second class Library and XML related operations. Actually senior programmers want independent class to read and write XML. I make this class static.
In another situation I have class of chartData. In that class I want methods like whether Line of Axis,series of chart is valid or not. Also whether color of chart stores in ARGB format or plain color name. They do not want those methods in same project. Now can I make class static or create object.
If your class does not have to manage state then there is absolutely no reason to not declare it static.
In C# some classes even have to be static like the ones that have extension methods.
Now if there's a chance that it requires state in the future, it's better to not declare it as static as if you change it afterwards, the consumers will need to change their code too.
One concern is that statics can be harder (not impossible) to test in some situations
The danger of static classes is that they often become God Objects. They know too much, they do too much, and they're usually called "Utilities.cs".
Also, just because your class holds methods only doesn't mean that you can't use a regular class, but it depends on what your class does. Does it have any state? Does it persist any data that's being modified in your methods?
Having static classes is not bad, but could make you think why you have those methods there. Some things to keep in mind about that:
if the methods manage behavior for classes you have in your project, you could just add the methods to those classes directly:
//doing this:
if(product.IsValid()) { ... }
//instead of:
if(ProductHelper.IsValid(product)) { ... }
if the methods manage behavior for classes you can't modify, you could use extension methods (that by the end of the day are static! but it adds syntactic sugar)
public static bool IsValid( this Product product ) { ... }
//so you can do:
if(product.IsValid()) { ... }
if the methods are coupled to external services you may want to mock, using a non-static class with virtual methods or implementing an interface will let you replace the instance with a mock one whenever you need to use it:
//instead of:
StaticService.Save(product);
//you can do:
public IService Service {get;set;}
...
Service.Save(product);
//and in your tests:
yourObject.Service = new MockService(); //MockService inherits from your actual class or implements the same IService interface
by the other hand, having the logic in non-static classes will let you make use of polymorphism and replace the instance with another one that extends the behavior.
finally, having the logic in non-static classes will let you use IoC (inversion of control) and proxy-based AOP. If you don't know about that, you could take a look at frameworks like Spring.net, Unity, Castle, Ninject, etc. Just for giving you an example of what you could do with this: you can make all the classes implementing IService log their methods, or check some security constraints, or open a database connection and close it when the method ends; everything without adding the actual code to the class.
Hope it helps.
It depends on the situation when to use static classes or not. In the general case you create static classes when you do not need to manage state. So for example, Math.cs, or Utility.cs - where you have basic utility functions - eg string formatting, etc.
Another scenario where you want to use static is when you expect the class to not be modified alot. When the system grows and you find that you have to modify this static class alot then its best to remove the static keyword. If not then you will miss out on some benefits of OOD - eg polymorphism, interfaces - For example you could find that I need to change a specific method in a static class, but since you can't override a static method, then you might have to 'copy and paste' with minor changes.
Some senior programmer argue that do not use static class.
Tell him he is a traineee, not even a junior. Simple. The static keyword is there for a reason. if your class only has methods without keeping state - and those cases exist - then putting them into a static class is valid. Point.
Can someone knows in C# language there is any harm in using static class.
No. The only valid argument is that your design isbroken (i.e. the class should not be static and keep state). But if you really have methods that do not keep state - and those cases exist, like the "Math" class - then sorry, this is a totally valid approach. There are no negatives.

Custom Exceptions and reducing duplicated code

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.

Are there standard naming conventions for this example of The Template Method Pattern?

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.

Categories

Resources