How to avoid catching generic exceptions - c#

In my processing I would like to log any error along with the user and code details and proceed on with my work.
I am currently using a try catch block which includes a generic catch, but is catching a generic exception is a bad thing? Such as the exception could be a stackoverflowexception or outofmemoryexception and need to be handled differently.. .
But I am not sure how to avoid catching these fatal exceptions. I am looking for suggestions.
Why I want to catch all exceptions
Because I don't want a failure in one form's processing to affect the others in the loop.
Why I am catching specific exceptions:
I understand I can look for stackoverflowexception, outofmemoryexception etc... but my point is, there could be many of them...looking for each and every would make my code lengthy. I am not sure if that is the best process.

But I am not sure how to avoid catching these fatal exceptions
Well, 2 things.
First, you can always rethrow them, for example, after logging.
Second, you can catch every exception you want and if you do not catch System.Exception then all you do not catch will bubble up - that is C# 101 for beginners, so if you have a problem with that, back to reading the documentation about exceptions in general.

Exceptions cascade down. If you want to handle certain exceptions differently, implement a different catch block.
try
{
ThisMethodMayThrowException();
}
catch(StackOverflowException ex)
{
//handle a StackOverFlowException
}
catch(OutOfMemoryException ex)
{
//handle a OutOfMemoryException
}
catch(Exception ex)
{
//handle all other types.
}
In general though, you should only plan to handle expected exceptions. For example, if you're writing to a file that you expect to exist, you might anticipate a FileNotFoundException. If you tried to handle every possible exception, your code would become quite long and unwieldy, to little benefit.
Microsoft provides excellent info on exception handling.

Reverse your thinking... because the advice catching generic exception is being misinterpreted.
Handle all exceptions which are known explicitly (do the log and continue processing), but always have a generic catch all exception handler to stop all processing and handle that unknown.
In your example an overflow exception could comprise data or let malicious actors take over the system in unexpected ways; hence continuing on, should not be done.

If you know all the exceptions you want to catch, you write a catch block for each specifically:
try
{
}
catch (IOException)
{
}
catch (InvalidCastException)
{
}
...
Then all the ones you don't want to catch (and thus allow to potentially take down your program) will keep bubbling up.

I am currently using a try catch block which includes a generic catch,
but I have heard from many people that catching generic exception is a
bad thing(as the exception could be a stackoverflowexception or
outofmemoryexception).
You should know which Exception types your method calls might throw.
It could be discovered either at the Method documentation, example:
/// <exception cref="DivideByZeroException">Why it's thrown.</exception>
public void MethodThatMightThrowDivideByZeroException(){...}
or by looking at the Method code, example:
throw new DivideByZeroException();
That way, you would be able to catch it easily:
try
{
ThisMethodMayThrowException();
}
catch(DivideByZeroException ex)
{
//handle a DivideByZeroException
}

Related

Catch exception not of a type

Is there a difference when catching exceptions not of a type between :
try
{
...
}
catch (TaskCanceledException)
{
throw;
}
catch (Exception exception)
{
...
}
and :
try
{
...
}
catch (Exception exception) when (!(exception is TaskCanceledException))
{
...
}
Yes, there is.
In the second block of code you are filtering on general exception type. It is not meant to be filtered, what happens if "TaskCanceledException" is thrown? you are not handling it and it will escalate to enclosing code. You are not really meant to filter anything on "Exception" type since it is the parent for all other type of exception and it is the last point of handling exception. A better option would be to create a custom exception and put them in separate block of catch and filter on them if needed.
The first option is more correct compared to the second one. Though you should not be throwing any exception and stay away from them, unless it is a complete deal breaker. On top of that what is the point of putting a catch block with Exception type bellow TaskCanceledException catch block which throws exception? You are basically telling that "I Would like to handle all exception" when using catch with Exception type, but at the same time you through one exception in exceptional case. Either throw the original exception or handle them.
Hope this makes sense.
Refer to this link Stackoverflow
Catch blocks already allow you to filter on the type of the exception:
catch (SomeSpecificExceptionType e) {...}
The when clause allows you to extend this filter to generic expressions.
Thus, you use the when clause for cases where the type of the exception is not distinct enough to determine whether the exception should be handled here or not.
The Dixin's Blog explained the difference with code example and VS screenshots.
Exception filter does not unwind the stack, and catch block does unwind. When executing catch block, this catch block’s method becomes the top frame of the stack. As a result, all the methods called by current method are removed from the stack. In contrast, exception filter can be helpful for runtime debugging. For example, if above Catch method is executed:

C# Error handling catch blocks

Why is it adviced most of the time that we should not trap errors like "Exception" but trap errors that we expect as developers.
Is there a performance hit in trapping generic errors or is it recommended from a best practice point of view?
try
{
// Do something
}
catch(Exception e)
{
//Log error
}
The best practice is to catch specific exception first and then move on to more generic ones.
Exception Handling (C# Programming Guide)
Multiple catch blocks with different exception filters can be chained
together. The catch blocks are evaluated from top to bottom in your
code, but only one catch block is executed for each exception that is
thrown. The first catch block that specifies the exact type or a base
class of the thrown exception is executed. If no catch block specifies
a matching exception filter, a catch block that does not have a filter
is selected, if one is present in the statement. It is important to
position catch blocks with the most specific (that is, the most
derived) exception types first.
For your question:
Why is it adviced most of the time that we should not trap errors like
"Exception" but trap errors that we expect as developers.
An example would be to catch NullReferenceException. Its never a better practice to catch NullReferenceException, instead one should always check for object being null before using its instance members. For example in case of string.
string str = null;
try
{
Console.WriteLine(str.Length)
}
catch(NullReferenceException ne)
{
//exception handling.
}
instead a check should be in place for checking against null.
if(str != null)
Console.WriteLine(str.Length);
EDIT:
I think I got the question wrong, If you are asking which exception should be caught and which shouldn't then IMO, those exceptions which can be dealt with should be caught and rest should be left in the library so they can bubble up to upper layer where appropriate handling would be done. An example would be Violation of Primary key constraint. If the application is taking input(including primary key) from the user and that date is being inserted into the database, then that exception can be caught and a message can be shown to user "Record already exists" and then let the user enter some different value.
But if the exception is related to the foreign key constraint (e.g. Some value from the dropdown list is considered invalid foreign key) then that exception should bubble up and a generic exception handler should log it in appropriate place.
For example in ASP.Net applications, these exception can be logged in Application_Error event and a general error page can be shown to the user.
EDIT 2:
For the OP's comment:
if at a low level if there would be a performance degeradation in
catching a generic error inspite of knowing if the error is
sqlexception
Even if there is going to be any performance difference it should be negligible. But Catch the specific exception, if you know that the exception is going to be SqlException then catch that.
You should only catch exceptions what you can handle. Exception is too generic so most of the time you cannot say you can handle that. It is a little funny but you should only catch exception that you except :)
There are situation when you need to catch Exception but rare and you should avoid it most of the time. Usually it indicates some design problem.
Check Eric Lippert's blog (Vexing exceptions) about best way to handle exceptions.
• Don’t catch fatal exceptions; nothing you can do about them anyway, and trying to generally makes it worse.
• Fix your code so that it never triggers a boneheaded exception – an "index out of range" exception should never happen in production code.
• Avoid vexing exceptions whenever possible by calling the “Try” versions of those vexing methods that throw in non-exceptional circumstances. If you cannot avoid calling a vexing method, catch its vexing exceptions.
• Always handle exceptions that indicate unexpected exogenous conditions; generally it is not worthwhile or practical to anticipate every possible failure. Just try the operation and be prepared to handle the exception.
Using exception handling more often than required is infact a lazy way of programming more than anything. Say you have a DataTable and you want to access the first row.
public DataRow AccessFirstRow(DataTable dt)
{
try
{
return dt.Rows[0];
}
catch (Exception e)
{
//There isn't a first row or dt is null
}
}
Instead of
public DataRow AccessFirstRow(DataTable dt)
{
if(dt != null)
if(dt.Rows.Count > 0)
return dt.Rows[0];
//If we can't access dt, then don't
return null;
}
My rule of thumb is:
Exceptions should only be used in EXCEPTION-al circumstances.
If you do decide to handle them though, as mentioned handle specific exceptions you know you might encounter instead of generic exceptions.
It's a best practice thing. The idea is that you should quickly handle the known exceptions explicitly while having more general ones higher up in the program as unexpected exceptions are likely caused by some more major/fundamental error.
Catch those exceptions which you intend to handle. You will usually want to handle particular exception in such context (method) where you have enough information for dealing with error reported (e.g. access to objects used for clean-up).
If code within try block throws different types of exceptions, you might want to handle some exceptions within the same method and re-throw others in order to handle them in the caller method (as in that context you have resources for handling those exceptions).

Exception Handling in C# with Entity Framwork 4

I use asp.net 4, c# and ef4.
I would like to know what is the best way to catch an generic Exception from Entity Framework.
At the moment I use Exception it is appropriate?
How catch a more specific one?
Thanks for your time.
try
{
context.DeleteObject(myLockedContent);
context.SaveChanges();
}
catch (Exception)
{
e.Cancel = true;
}
It's rarely good to catch generic exceptions and just cancel them. Exceptions are there to help you ensure you code can act appropriately.
You can catch specific exception types just as you have for the generic (albeit with the identifier you have missed on your example) thus:
catch (OptimisticConcurrencyException ex)
{
// Do some real work to resolve the exception
}
The exception type specified in the catch statement tells the runtime to catch that specific and any child exceptions. As a result you need to organise your catch statements from the most specific exception to the least, i.e. :
catch (OptimisticConcurrencyException ex)
{
// Do some real work to resolve the specific exception
}
...
catch (Exception ex)
{
// Do some real work to resolve the generic 'catch-all' exception
}
Do not do that.
You are hiding errors which could severely affect the reliability of your application. An exception is thrown for a reason, just continuing on like nothing have happened is just wrong.
You're method cannot return the result as promised, which will affect all code that use it. But the calling methods will not know about the exception and will in worst case continue as nothing have happened and therefore produce undesired results.
You should only use catch all
a) when wanting to wrap exceptions at layer boundaries (but do include the original exception).
b) when the exception have propagated to the top layer (which would terminate your application if the exception is not caught).
Other than that, only catch exceptions when you can handle them. That means that you, by catching the exception, can return the result that the caller expects.
the way you are catching in your example is bad, always log the exception somewhere and somehow, for example on a text file or to an SMTPAppender, you can use Log4Net and get it running in very short time with minimal coding from your side.
Said so, it really depends if you want to handle different exceptions differently, for example if a file was not found you can decide to create it or to tell the user to do something, if the more general exception is thrown you may act differently...
just keep in mind you should put all your catch clauses from the more specific to the more generic one, in your example, if you have multiple catches, the one you wrote should be put in the end.

When to use and when not to use Try Catch Finally

I am creating asp.net web apps in .net 3.5 and I wanted to know when to use and when not to use Try Catch Finally blocks? In particular, a majority of my try catch's are wrapped around executing stored procs and populating textfields or gridviews? Would you use Try Catch EVERYTIME when you execute a stored proc and populated a data display control?
My code block usually looks like:
protected void AddNewRecord()
{
try
{
//execute stored proc
// populate grid view controls or textboxes
}
catch (Exception ex)
{
//display a messagebox to user that an error has occured
//return
}
finally
{ }
}
The answer is "it depends".
You might want to use a try{...} catch {...} around every atomic operation so that if there is a problem you can roll back to the last good state (using transactions). This may be one or several stored procedures - it depends on your application.
If you are trapping the exception, make sure you are explicit in which exceptions you catch. You shouldn't have catch (Exception ex) or catch() - known as "catch all" exception handling - but have specific catch statements like catch (IndexOutOfRangeException ex) (for example) instead.
However, if you can't handle the exception or there's nothing you can do to clean up, then you shouldn't trap it.
You should only use try catch, when you intend on handling the exception in the catch block. What I mean by handle is, log the error, choose a different path because of the error etc. If you merely intend on re-throwing it, there is no point in having try catch.
As others have said, it depends. I tend to use try/catch/finally blocks in two situations:
I need to handle the Exception in some way other than simply re-throwing it.
I need to clean up some resources in the finally block.
Other than those two situations, I let the calling code handle any Exceptions that might happen.
In addition to what others have said, be sure to avoid doing this:
try
{
throw new ApplicationException("Fake sql ex");
}
//catch and do nothing. swallowing exceptions
catch(Exception){ }
Most of the time you should not be catching exceptions. Some places where it does make sense to catch an exception e.g.,
When you can recover from that specific exception.
When you need to log it or report it (e.g,. to the user)--usually at the top level in your code.
When the caller of your code can not handle exceptions, so you need to convert them into some other error format.
Also, the using block statement can be used to actually call Dispose on IDisposable objects, which removes the need for try...finally.
What is the Exception you are expecting from the stored proc? Providing you don't use pokemon exception handling and know exactly what your application is expected to do, anything that doesn't fit the specific Exception you want to to catch will be caught by the Application object.
In other words don't use catch {} or catch (Exception), but specialized exception handling:
catch(SqlException e)
{
// Log stacktrace and show a friendly error to your user
}
The Application.Error event is where unexpected behaviour should be caught and is easier to trace than simply having a customer return to you saying "my fields aren't displaying anything".
Use "try catch" within the innermost loop that should keep executing when a particular exception occurs. Be mindful that if you have a loop that executes 10,000 times and an exception occurs on e.g. the tenth repetition which won't affect the other 9,990 it may be useful to catch the exception and let the loop keep going. On the other hand, if the exception indicates a fault that suggests the 11th, 12th, 13th, etc. times through the loop are also going to fail, it would be much faster to let the exception kill the loop than to keep retrying an operation that isn't going to work.

How often should I use try and catch in C#?

When writing a C# application whose #1 priority is to never crash, how often should I used a try-catch block?
Can I encapsulate all the statements in a method in try-catch blocks?
public void SomeMethod()
{
try
{
// entire contents of the function
// library calls
// function calls
// variable initialization .. etc
}
catch (Exception e)
{
// recover
}
}
What are the downsides to wrapping everything in try-catch blocks?
The only down side is when an exception is actually thrown. There is no overhead for wrapping the code, except for when exceptions occur.
Also, you don't want to use try/catch for control flow. Consider this (bad code):
try {
FileStream fs = File.Open("somefile.txt", FileMode.Open);
} catch (Exception ex) {
MessageBox.Show("The file does not exist. Please select another file");
}
You'll get more performance from some thing like File.Exists. such as:
if(!File.Exists("somefile.txt"))
MessageBox.Show("The file does not exist.")
EDIT:
found the MSDN direct quote:
Finding and designing away
exception-heavy code can result in a
decent perf win. Bear in mind that
this has nothing to do with try/catch
blocks: you only incur the cost when
the actual exception is thrown. You
can use as many try/catch blocks as
you want. Using exceptions
gratuitously is where you lose
performance. For example, you should
stay away from things like using
exceptions for control flow.
This is a big topic. Start here for some excellent discussion of Exception handling best practices and be prepared for a religious war...
Code Analysis Team Blog
Martin Fowler - Fail Fast
MSDN on Exception Handling
Checked vs Unchecked Exceptions
My own opinion is that for the most part you use "try/finally" a lot, but "catch" very little. The problem is that if you attempt to catch and handle Exceptions in the wrong instances, you may inadvertently put your application in a bad state. As a rule, use dev and test to learn where you actually need to handle an exception. Those will be places that you can't check. i.e. you shouldn't really need to handle nullreference or filenotfound because you can proactively check for those. Only exceptions you know may happen, but you can't do anything about. Beyond that, for the sake of your data's state, let it crash.
If you are swallowing exceptions, it generally means you don't understand your program or why you are getting an exception. Catching System.Exception is the poster child of code smells...
Actually, I very rarely use a catch block except for logging purposes. finally is much more common for me. Most times, lock or using do everything I can usefully do (and indeed, that is a finally also).
Eric Lippert has a blog entry on exceptions that may be useful.
The key to this question is the following line:
// recover
To be able to recover, you have to know what and how to recover. And that's assuming it is possible to recover, which quite frequently it isn't.
You should only use the catch part of try/catch/finally to swallow an exception when you know how to handle the exception, when you know how to recover from it, and when you're sure you can do so without leaving the application in an inconsistent or invalid state.
If you can do this for all possible exceptions in all method calls in your application then go right ahead, otherwise you might need to re-think your #1 priority (sometimes failing fast is a better options than trying to keep an application alive when something has gone wrong, and having a much harder to debug crash later on).
Generally IMO it is better to put smaller chunks that are out of your control in a try catch. If you say:
try
{
//anything that could possibly go wrong
//This kind of thing is only good for Logging IMO and could be done in
//Global.asax
}
How could you possibly know what to do in your catch method cause it could be anything...
Its much better to go:
try
{
//divide user imputs
}
catch(DivideByZeroException)
{
// tell user bad inputs ect....
}
catch (Exception e)
{
//If you choose to throw the exception you should
//***********************
throw;
//VS
throw ex; //Throw ex will restart the stack trace
// recover
}
finally
{
//Clean up resources and continue
}
In which finally is always run
There is performance overhead for try blocks, if you do that your entire function will run slower then it otherwise would. catch (Exception e) is also a bad idea, if you catch you want to do something useful with what you caught, and if you catch all exceptions it is impossible to know what you should be doing.
You can do this, although almost in any given environment you're running in, there's a global exception handler where you can catch and handle even unknown errors.
For web apps, there's the Global.asax, for a console program, just wrap your Main() in a try/catch, for services, there's AppDomain.CurrentDomain.UnhandledException, etc.
You should wrap sections where you can predict what the exception might be in more specific blocks, but the global exception handlers should greatly simplify your code and help you out.
You should only catch and stop the exception without rethrowing it if you can meaningfully handle it. Otherwise it is an error and it should propagate up.
I assume that when they say "this app should never crash" there is an implicit requirement that it behaves correctly. Only stoping exceptions that are meaningfully handled satisfies the behaving correctly requirement.
Typically an app will have a single top-level catch block to catch and log unhandled exceptions. These should occur infrequently (and perhaps your requirement can be interpreted to mean these should not happen at all). If you catch and stop exceptions anywhere else in your code, you risk not discovering these problems. If you catch log and stop in lots of other parts of your code, you have a poorly constructed app from the perspective of separation-of-concerns.
I try to avoid try catch blocks generally. I prefer to use blocks to force the user into obeying the rules of an application. For example, if a user should only enter an int that is equal to or less than an int x I'd use:
if (input > x)
{
Console.WriteLine("Invalid input. Please enter a number that is equal to or less than x.");
{...}
}
rather than using:
catch (IndexOutOfRangeException)
{
//error message here
}
From my own personal experience I find it easier to write as you can avoid encapsulating code in a try block (guarding code).
Of course, there will always be times where using try catch is unavoidable - I just like to work around it where possible.
Our current application has a similar mandate: Never crash. Always back out gracefully. To do this, you have to make sure that every line of code is either enclosed in a try-catch block or only called by code that its exceptions can bubble up into.
Also, to protect against uncaught exceptions, we attach an UnhandledExceptionEventHandler to AppDomain.CurrentDomain.
You should use them anytime a piece of code can thrown an exception.
You have to be careful, catching general exceptions is never a good idea. You have to decide which layer you want to handle them.
Meaning the deeper you are you want to catch very specific excpetion and go more general. In a database catch the SqlException. As you go higher in the stack you catch more exceptions to finally catching the general exception at the very top.
That way you can deal with each exception on a case by case basis. A general exception you aren't going to know what to do with.
public void functionName
{
try
{
//your codes
//sometimes 'return' shows exceptions
}
catch(Exception e)
{
messagebox.show(e.Tostring()); //to know what is the exception
}
finally
{
}
}
try catch in c#:
try{
}
catch (NullReferenceException en)
{
}

Categories