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:
Related
Disclaimer: It is well known that catch (ex) { throw ex; } is bad practice. This question is not about that.
While digging through Microsoft reference sources, I noticed the following pattern in a lot of methods:
try {
...
} catch {
throw;
}
No logging, no debugging code—just a plain simple catch { throw; }.
Since, obviously, the guys at Microsoft should be fairly proficient in the use of C#, what could be the point of doing that instead of just omitting the catch block (and the try statement) altogether? Is there a technical reason for coding like this, or is it purely a stylistic choice?
Note: I don't know if it is relevant, but all such instances I could find also contain a try-finally block nested inside the try clause of the try-catch block.
It affects when exception filters run.
Given
void f() {
using (var x = AcquireResource()) {
x.DoSomething();
x.DoSomethingElse();
}
}
versus
void f() {
try {
using (var x = AcquireResource()) {
x.DoSomething();
x.DoSomethingElse();
}
} catch {
throw;
}
}
with
void g() {
try {
f();
} catch (Exception ex) when (h()) {
// ...
}
}
The first version of f would allow the filter h() to be called before x got disposed. The second version of f ensures that x is disposed before external code is run.
In the code you link to, SqlConnectionHolder is used a lot, and catch { throw; } blocks are all around the use of SqlConnectionHolder.
As C# Specification describes:
When an exception occurs, the system searches for the nearest catch clause that can handle the exception, as determined by the run-time type of the exception. First, the current method is searched for a lexically enclosing try statement, and the associated catch clauses of the try statement are considered in order. If that fails, the method that called the current method is searched for a lexically enclosing try statement that encloses the point of the call to the current method. This search continues until a catch clause is found that can handle the current exception, by naming an exception class that is of the same class, or a base class, of the run-time type of the exception being thrown. A catch clause that doesn't name an exception class can handle any exception.
Once a matching catch clause is found, the system prepares to transfer control to the first statement of the catch clause. Before execution of the catch clause begins, the system first executes, in order, any finally clauses that were associated with try statements more nested that than the one that caught the exception.
in case of exception runtime first looks for catch clause that can handle it, which involve executing any associated exception filters. Undiscriminating catch block interrupt that search and make all nested finally blocks to be executed immediately.
That can be useful when you want to prevent caller from executing arbitrary code (in form of exception filter) before finally block. For example, when finally block affect security context of current thread.
Also, if exception will not be caught by any catch clause, then it will lead to thread termination. And in that case C# Specification did not provide any guaranty, that any finally block will be executed at all.
If the search for matching catch clauses reaches the code that initially started the thread, then execution of the thread is terminated. The impact of such termination is implementation-defined.
The code you linked is actually a very good example.
In my eyes, one should only use try catch blocks when dealing with things outside of their control, like file systems, external things basically.
In the code you linked the try catch is around the database stuff.
What this means is that by using this way of coding, they make sure there are no leaks, no connections remain open.
If anything goes wrong, such as wrong connection string, missing tables, whatever, the code is going to continue to execute, it will gracefully close the connection as shown in the finally block and it will finally throw meaning it will allow the client of that code to get the proper exception, get the entire stack as well and let them decide what to do when that happens.
To be honest I quite like what they did there.
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
}
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
the difference between try/catch/throw and try/catch(e)/throw e
Pardon my stupidity, anyone knows difference between them?
try
{
return 1 / 0;
}
catch (Exception)
{
throw;
}
try
{
return 1 / 0;
}
catch
{
throw;
}
try
{
return 1 / 0;
}
catch (Exception e)
{
throw(e);
}
Will catch and rethrow only exceptions derived from Exception.
Will catch and rethrow any exception. (Edit: Since CLRv2, all exceptions are derived from Exception so this is identical to 1. See Eric Lippert's comment below).
Will catch any exception derived from Exception and throw it again, thus resetting the stack trace of the exception.
A catch clause without arguments can catch any type of exception. This is sometimes referred to as the "general" catch clause. You should probably never use this in a production application, but I suppose it might sometimes be useful for debugging. It looks like this:
catch
{
}
A catch clause can also specify the particular exception class that you want to catch. You should always do this in your applications because you're only supposed to catch exceptions that you know how to handle. For example, you might want to catch a DivideByZeroException; you'd do it like this:
catch (DivideByZeroException)
{
}
Of course, that has the side effect that you're unable to refer to the exception class itself inside of the catch block because you haven't assigned it to a variable. If you need to call properties or methods on the instance of the exception class that you catch, you'll need to include a named variable in the catch statement. That is probably what you're most used to seeing, and it looks like this:
catch (DivideByZeroException ex)
{
// do something with ex here
}
Then there are two ways to write the throw() statement, and it matters which one you choose:
The first just looks like this:
throw;
It is written without any arguments, and the purpose is to rethrow the caught exception while preserving the stack trace and as much information about the original exception as possible.
(There are still some edge cases where this can cause you to lose the stack trace, but generally this is much preferred over the alternative below.)
The second option passes an instance of an exception class as an argument, and looks like this:
throw(ex);
or this:
throw ex;
This also rethrows the specified exception, but as mentioned above, it has the downside of losing some of the stack trace information that tells you what method was responsible for throwing the exception. It's rare that you'll use this except to throw a new exception object that you create in the same method.
For example, if you wanted to catch a low-level exception and wrap it within a new exception object for consumption by a higher-level function, you would use this form.
The first two are equivalent.
The third one should generally be avoided: it rethrows the exception from its own stack frame, losing information about the original frames in the process.
catch (Exception) - Catches anything that derives from Exception class
catch (Exception e) - Catches anything that derives from Exception class and assign it to the variable e, which you can use.
catch - catches anything thrown.
There is no difference between example 1 and 2. Both rethrows the original exception, and both catches the general Exception. You would use example 1 if you wanted to catch a more specific exception, such as DivisionByZeroException.
For the last example, you are not re-throwing the exception; but throwing the same exception object that you caught. This causes the exception stacktrace to be re-set to the location where you throw it - which might be a problem because the stacktrace then does not point to the location in code, where the error actually occured.
The difference is that throw e; will throw an exception with a different stack trace. See this accepted answer.
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.
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.