Create a guaranteed exception safe method in C# - c#

I recently implemented a function which logs object contents using JSON.SerializeObject.
To cut a long story short, the idea was, that this function would be used in our newly implemented logging mechanism, to track objects when needed, based on system parameterization.
One absolute requirement for the entire logging mechanism, was that it should never throw exceptions, because it would be used extensively. Any developer should be able to use it and under no circumstances should this function cause any interruption in code flow. In case of failure, any call should simply be skipped.
After implementing it and having inspected and handled every exception that I could think of, I decided to wrap the entire functionality in an outer try-catch block, just in case.
Like so:
public static void TrackObject(object obj)
{
try { Console.WriteLine(JsonConvert.SerializeObject(obj)); }
catch { Console.WriteLine("Failed to track object."); }
}
After passing all tests with flying colors, I fired up the main application to do some actual environment testing.
To my surprise, due to a Nuget misconfiguration, my function caused an exception (System.IO.FileLoadException) after it was called, but before it entered the try-catch block and so it propagated back to the main application, causing havoc to code flow.
This got me thinking.
There are ways for exceptions to be thrown while calling the function but before a handler kicks in. There are also cases where an exception is simply unacceptable.
My current solution, was to create a wrapper function, which simply calls the actual function inside a try-catch. But this looks ugly and wrong. Plus I am not sure it is a bullet proof solution.
public static void TrackObject(object obj)
{
try { PrivateTrackObject(obj); }
catch { Console.WriteLine("Failed to track object."); }
}
private static void PrivateTrackObject(object obj)
{
Console.WriteLine(JsonConvert.SerializeObject(obj));
}
Is there a way to create a bullet-proof, no-way in hell, exception free method?
Or at least is there a definitive list of exceptions that can occur on a method call?
PS. The compiler warned me about the version mismatch, but I didn’t see it the first time.
PS2. I have created a sample project for anyone who wishes to see this issue in action.
https://drive.google.com/open?id=15BDrLNn87gsMHc9pQ-TgyDMSLQxDBq18

Is there a way to create a bullet-proof, no-way in hell, exception free method?
No. Even if the method is literally empty you can always have a thread abort exception thrown, or a stack overflow exception if there isn't enough space on the stack to call that method, or it could result in an out of memory exception.
is there a definitive list of exceptions that can occur on a method call?
If it's arbitrary code (i.e. from a delegate) then no. It could always be a custom exception of some type that didn't even exist when you wrote your code.
Also note that in your situation you need to be concerned about any possible exceptions that could be thrown in your catch block, if you just want to try handling normal exceptions (unlike the ones mentioned above) that happen in your try block. Just logging the exception could fail. In your example of using the console there could be problems with standard output that result in an exception. If you're really going for this code never throws you'd need to try to log the exceptions, but have other backup logging options for when they aren't working (and if you really can't throw, which as mentioned by others, is almost certainly a bad idea, then you need to be willing to go on without logging if logging your exceptions is failing).

Related

Returning exceptions

I would like to return exceptions from a method, like this:
Exception f()
{
try
{
// Do something.
return null;
}
catch(Exception e)
{
return e;
}
}
I know that this is considered bad practice, but are there any technical reasons to avoid this?
EDIT: This is not the same question as Is it bad practice to return Exceptions from your methods. I am asking about technical reasons, not best practices.
There are no 'technical' reasons to avoid this. That is, the .Net framework will happily support this type of arrangement.
Also be aware that throwing exceptions incurs a performance penalty, so avoid relying on throwing exceptions for your normal control flow. They should only be used when something has genuinely gone wrong.
It's also fine to instantiate an exception without throwing it:
Exception f()
{
return new Exception("message");
}
Here are some reasons that you may want to rethink that design.
Firstly, new ArgumentOutOfRangeException(...); does not produce your exception stack trace is not generated until you throw it. This may confuse debugging efforts further down the stack. The stack trace will literally be lying.
Secondly, Exception is heavier than some sort of status enum to indicate what type of error occurred. It is hard to see what benefit you are getting out of the response object being of type exception. It presumably requires the caller to subsequently perform a bunch of if (response is FileNotFoundException) .... and decide what they want to do for each.
This means that you lose the ability to differentiate between expected exceptions and unexpected exceptions in a given function. Take a well understood unique constraint violation. Somewhere within your call, or something you call, an insert statement is rejected by the DBMS because of another record having this value. Depending on your use case, this is either an exceptional circumstance indicating something somewhere went very wrong (eg, a corrupt data file), or a result in its own right (eg, a booking system that allocated a seat to someone else between showing you its availability and you accepting). In the first case, you would want your caller to bubble that up to the point in the application which knows what to do about that. In the second, you can safely return that for the caller to do its business.
Thirdly, it is a violation of the principle of least astonishment. Exceptions, by design, are bail out by default. Unless I explicitly catch an exception, it will bail out of my method, excecuting the stuff in my except and finally blocks, nicely calling dispose for me at the end of any using blocks and repeat in my method's caller. What it will never do is execute the code of mine that might be relying on the results of that method call.
Your design here is ignore by default. Unless I explicitly check the result and choose to throw, it will carry on executing my code. Consider this contrived example:
Exception error;
error = GetData(out data);
if (error is DbException) return error;
if (error is ArgumentOutOfRangeException) return error;
// if (error is ....... etc
error = ApplyChangesToData(data);
// if (error is ....... etc
error = SaveData(data);
// if (error is ....... etc
Now the stakes are high if I miss something, because my partially constructed data object may then make its way through the ApplyChangesToData method and then get saved back to the database in corrupted form. This could be as simple as you not anticipating that internally GetData hits a SocketException or an OutOfMemoryException. It isn't just making your abstraction a bit leaky, it means that unless you do have a leaky abstraction, your code cannot be safely written. My code has to know whether you are talking to SqlServer or Oracle or Mongo or whatever so I can anticipate all the possible exceptions you may retun and include them in my if lines. Of course I could put an else in and throw any exception object, but presumably you don't want to do this or you wouldn't be catching it in the first place.
On the other hand, if you were allowing the exceptions to bubble up, and I was confident in what such an exception meant in my context and could still meaningfully carry on, I still have the option of catching that exception and reacting to or suppressing it.
The only exception (pun unintended) that I can think of is at the edge of an API service layer, where you might want to log the exception then return a generic "something went wrong on the server" rather than blab your dirty laundry and expose security sensitive information over a public facing endpoint.
I hope I have convinced you (or , if not, at least someone in the future reading this suggestion) not to go down that dragon-filled path.

Is it a good practice to cache exception instance in C#

I'm trying to find an answer on that question, which is:
Is the following code is a good practice?
Should I try to reproduce it wherever it's possible or not? and if not, why?
public class ExceptionHelper
{
private static readonly HttpException _errorReadingRequest = new HttpException(500, "Error reading request. Buffer is empty.");
public static Exception ErrorReadingRequest { get { return _errorReadingRequest; } }
}
public class ExceptionThrower
{
public static void ThrowCached1()
{
throw ExceptionHelper.ErrorReadingRequest;
}
// ...
}
I've tried to throw in several places the cached instances and it seems to preserve the stack trace, from MSDN,
The stack trace begins at the statement where the exception is thrown
and ends at the catch statement that catches the exception. Be aware
of this fact when deciding where to place a throw statement.
I understand that as "It stores the stack trace at the throw, not at the creation". However, I'm wondering if there could be a problem when multiple threads try to throw the same cached instance of exception.
On the same MDSN page, they are using an helper function and it seems in the framework, they are doing the same: helper function which recreates the exception and throw.
Note: I know it's not a common case because most of the time, you want a specific message to be stored in the exception so it's easier to understand what's happening.
Maybe the question is just is throw keyword thread safe or not?
Context:
I've stumble upon this kind of code, while code reviewing some performance touchy application code. The goal is to create the maximum of instance during startup and then never (or almost never) instances during execution, in order to limit the GC performance impact (especially because of heap fragmentation occuring with GCHandle thing). I had a bad feeling about this code but needed facts to support my refactoring.
Generally it makes no sense to have one cached exception. CREATING an object is fast. Exceptions shoudl be rare - and catching them has some overhead, as has throwing them. THere is simply nothing gained from having "one exception to rule them all", except:
Threading issues
More convoluted code
Totally ignoring coding standards I have seen in the last 20 years.
If any of those things are your goal - go along.
Maybe the question is just is throw keyword thread safe or not ?
The throw keyword is thread safe - you can have multiple threads throwing at the same time. Using the same exception though is going to get you into trouble, but it is not because the throw KEYWORD is not thread safe but because you maliciously violate thread safety by passing in the same data object.
Throwing an exception mutates that exception object. It stores the stack for example. This is a problem if you want to use the stack trace for logging purposes. You'll get randomly corrupted stacks.
Also, creating an exception object is cheap. This does not accomplish much.
#TomTom gave a great answer, I want just to point out the example for exception caching being a standard practice: TPL's Task class Exception property.
Sometimes, if the exception is thrown inside some asynchronous operation, it is a good practice to save the information about it for the moment you need the result of operation.
But! As TPL's programmers did, you should wrap the original exception inside the new one (for example, AggregateException) so you can see the original source and stacktrace of it.
As for the GC collection's performance hit, you can use other techniques. For example, if there are a lot of objects being created and after that being collected, try to use the structs for DTO-objects instead of classes. If they will fit into a stack size, they will be collected automatically after the method ends it's execution.

What happens to an exception in an async method if EndInvoke is never called?

Let's say I have the following code:
private delegate void DeadlyDelegate();
private void Deadly()
{
throw new Exception("DIE!");
}
public void DoStuff()
{
DeadlyDelegate d = Deadly;
d.BeginInvoke(null, null);
}
Now, there has already been much discussion about if EndInvoke() is needed (and the answer is yes), so I'm not asking that. But let's say that for whatever reason, EndInvoke is never reached (in my example, I simply don't call it, but we could imagine other reasons of how it could accidentally not ever be called).
First question: What happens to the exception? Does it completely disappear and never cause problems? Or does it finally get thrown as an unhandled exception during garbage collection, the same way that Task exceptions do if they are never observed? I've done much searching, both Google and SO, and haven't found the answer to this.
In my own code, I of course plan to always call EndInvoke(). But it would be nice to know what happens if, because of some unanticipated program path, EndInvoke somehow isn't called. I don't want my whole app to come crashing to a halt because of the unhandled exception (if there is one).
Second question: Whatever is the answer to the first question, is the same true of the built-in async calls in the .NET framework, like TcpClient.BeginConnect()? If that method throws an exception, will it simply disappear if I never call EndConnect(), or can it still cause problems?
Third question: (this should be trivial, but thought I'd double check) Is there any way some sort of strange unhandled/unobserved exception can happen in the async code between the BeginInvoke/Connect and EndInvoke/Connect calls? Or am I always guaranteed any exceptions will safely propagate to the point where EndInvoke/Connect is called?

An Exception Handling Class

What is the best practice for handling exceptions without having to put try/catch blocks everywhere?
I had the idea of creating a class that is devoted to receiving and handling exceptions, but I am wondering if its a good design idea. Such a class would receive an exception and then decide what to do with it depending on its type or error code, could even parse the stack trace for specific information, etc.
Here is the basic idea behind and implementation:
public class ExceptionHandler
{
public static void Handle(Exception e)
{
if (e.GetBaseException().GetType() == typeof(ArgumentException))
{
Console.WriteLine("You caught an ArgumentException.");
}
else
{
Console.WriteLine("You did not catch an exception.");
throw e; // re-throwing is the default behavior
}
}
}
public static class ExceptionThrower
{
public static void TriggerException(bool isTrigger)
{
if (isTrigger)
throw new ArgumentException("You threw an exception.");
else
Console.WriteLine("You did not throw an exception.");
}
}
class Program
{
static void Main(string[] args)
{
try
{
ExceptionThrower.TriggerException(true);
}
catch(Exception e)
{
ExceptionHandler.Handle(e);
}
Console.ReadLine();
}
}
I thought this would be an interesting endeavor because you would theoretically only need one or very few try / catch blocks around your main() method calls, and let the exception class handle everything else including re-throwing, handling, logging, whatever.
Thoughts?
There is actually a good reason why you don't see similar designs in production code.
First of all, such a design cannot help you reduce the count of try/catch pairs in your code (this should be obvious). It could help you reduce the number of catch statements for a given try, since you could just catch System.Exception and forward to the ExceptionHandler...
But what next?
Every exception needs to be handled differently. How would the ExceptionHandler know exactly what to do? You could try to solve this in a number of ways, e.g.:
Derive from ExceptionHandler and put the code to handle exceptions in virtual methods
Pass a number of Action<Exception> instances to the handler and have it invoke the proper one
Solution (1) would be worse than what you had before: now you need to create a whole new class for each try block and override a bunch of methods to end up with something worse than you had before (it's not immediately clear how the code in a particular class fits in the flow of your program). It would also leave another important question unanswered: you may need context (access to variables in the current scope) to properly handle the exception. How will you provide access to this context?
Solution (2) would actually end up quite similar to writing the catch blocks that we 've been wanting to avoid (each Action would be effectively the contents of a catch block). We end up doing the same thing, only in a more complicated and verbose manner.
There are also other issues:
What should ExceptionHandler do if it cannot handle the exception? Throwing it again will cause you to lose the original stack trace, in effect destroying all the good information in there.
What if there's a bug in ExceptionHandler? You can truse a try/catch. Can you trust code you wrote yourself to the same degree?
As for the ExceptionThrower... what benefit could it possibly offer over throw new Exception();?
Exception handling is a complicated matter already, and it's difficult enough to get it right without adding extra gears to the machine. Especially if they don't buy you anything new. Don't do it.
OK, this is probably not the answer you want but...
I am generally allergic towards the idea of a general exception handling class. You can almost hear how it is a contradiction in itself. An exception is an exceptional event. Exceptional events cannot be handled in a general manner, but needs tailored handling wherever they may appear, which essentially means that your code should to two things:
be defensive about any input in order to avoid exceptions in the first place
put try..catch blocks wherever it makes sense to catch and handle an exception (note that this means that you should not have try..catch blocks in all methods)
So, where does it make sense to catch and handle an exception? In short, where your code has knowledge that makes it capable of handling the exception. If it does not, let the exception bubble upwards to the caller. The only place where I think you should catch all exceptions and have some generic default behavior around what to do, it at the top level of your app. That is typically the UI.
Sorry, this is not a good idea. When you catch an exception in your code with a normal try/catch block surrounding the relevant section, you get to use two critical pieces of information to deal with the problem: the type of exception, and also where the exception occured.
With your arrangement, you have to deal with all exceptions knowing only what type of exceptions they are. You no longer know where the exception actually occured, so you really can't do anything about the problem other than to log it or show a message to the user.
Moreover, try/catch blocks often also include a finally block, in which you can make sure things happen even if an exception is thrown (like closing streams etc.). You don't have any way in your arrangement of dealing with this.
Proper exception handling can be tricky, and there is no magic bullet that will make it simple and straightforward. If there were, .Net would have already incorporated it.
We have a class in our code-base that has a pretty similar signature to the one you have proposed and I can tell you now that it has only bough misery and suffering!
Why do you have so many try-catch blocks in your code? Can you give some examples? Exceptions by their very nature "Exceptional", i.e.not that frequent! Not only should you not be catching exceptions that frequently, but also every exception is different and the same boilerplate code that works in one situation probably isn't suitable in many other situations.
Nobody said that exception handling was easy (or produced compact code) - you should think carefully about each situation you need to catch an exception and handle it appropriately - avoid catching exceptions that you don't need to handle.

ASP.NET MVC2 - number and location of try/catch(throw?) blocks

I'm in the process of thrashing through the whole exception-handling jungle, and I'm now trying to determine just how many try/catch blocks I need, and where to put them.
From my controller I have
CreateInvitation(fromUser, toUser);
which calls down to my BLL method
public static Invitation CreateInvitaton(User fromUser, User toUser)
{
try
{// see if toUser exists, then create the invitation}
catch
{// throw something, maybe?}
}
Do I actually need to re-throw it in that method? Won't it go back up the stack even if I don't re-throw it?
Do I need to wrap the controller's call in a try/catch block too, or is that redundant?
Maybe I don't need the try/catch block in the BLL method at all, and only need a try/catch block in my controller?
I'm looking at quite a few possible combinations here, and have no idea what the proper one is.
Thanks.
The exception handler, as written in your example, is doing absolutely nothing. (well, it's wasting a little bit of time, but it's doing nothing of use)
Had it been:
try
{...}
catch
{
// do something here.
throw;
}
Then the try/catch & throw would be needed.
Catch exceptions locally if and only if they indicate exceptional behaviour and can be fixed (or commented) locally.
Hard enough to find an example - here's one: I have some objects which need pessimistic lock. The lock is needed because writing to the object from the web application while another (background) app is reading it could lead to disaster. It is truly an exception, because it will happen very rarely. Moreover, I can do nothing about it beforehand (because the lock might have been acquired just before the next line is executed). However, I can retry in a few msecs, because I know chances are good the object is released again. Still, all this does not happen in the controller, but in a service class.
Don't use exceptions for expected conditions (invalid input, for example).
Also, I agree most exceptions in web applications cannot be handled except for logging a message (which should not be done in the controllers) and sending an error page. Lastly, when catching exceptions, make sure to do it right (catch a specific exception type, retrow with throw; not throw ex;)

Categories