Throwing an exception in a catch section - c#

I've got a new project. Every time you dealing with somebody else code it's an adventure.
Here is what I found:
try
{
.....
}
catch (InvalidOperationException e) {
throw e;
}
catch (Exception e)
{
throw;
}
Anybody has an idea why?
PS
Thanks everybody.
It really helps.
Here are some good sources that you recommended:
Why catch and rethrow an exception in C#?
http://msdn.microsoft.com/en-us/library/0yd65esw.aspx
http://msdn.microsoft.com/en-us/library/ms229005.aspx

Because whoever has written this doesn't have any understanding of how exceptions work in .NET.
If you don't do anything with an exception, don't catch it.
The code you posted would better be written as:
.....

The real danger of this (other than being completely useless...) is that it modifies the call stack. Others have briefly mentioned it in comments, but it deserves to be called out specifically.
When you have throw ex;, the previous call stack is blown away and replaced with the call stack at the point where throw ex; is called. You almost never want to do this. I will often catch an exception, log it, then rethrow the exception. When doing that, you want to just use throw;. This will preserve the original stack trace.

Makes no sense whatsoever to me, but not for the reason you might think.
Catching an exception is not the same thing as handling it. This try/catch block does no handling at all. I think a better, more honest, less verbose solution would have been to remove the try/catch and let the exceptions bubble up to where they can/should be dealt with.

i guess the application wants the outer method calling this to catch the exception instead but this is not the way it should be done, do check these references as they are somewhat similar
Why catch and rethrow an exception in C#?
http://winterdom.com/2002/09/rethrowingexceptionsinc

It is possible that they wanted to implement different handling for InvalidOperationException and other types of exceptions, so they wrote this code as a stub. But then this idea was abandoned so you see this code artifact.

you can improve this code by adding logging.
after every catch, log the information that you throw.
there are some opensource code available for logging.

Related

Exception issue

All the time, to avoid any run time error, I use the Exception handler:
as the following:
try
{
//My code which may raise an error.
}
catch (Exception ee)
{
string message = ee.Message;
ShowMessage();
}
My question is:
Is this considered as a good practice or bad practice? (I use the same
lines all the time)
What about the performance issue every time declaring a string?
When using those lines with a method which return a value, the
returning must be after the catch?
That's bad code. Actually very bad.
As all you do with the error message is to assign it to a string that you never use, you are effectively just catching the exception and ignoring it. This is pretty much the worst thing that you can do with an exception, as the program will continue on as if nothing happened, likely with unusable or corrupted data.
When catching exceptions:
Use a more specific Exception type, for example SqlException or IOException, so that you only capture the exceptions that you intend to catch, and that you know how to handle.
When catching an exception, either really handle it, or rethrow it so that it can be handled at a different level.
You should handle known issues first to improve performance, such as null references, empty strings, etc.
Use exceptions for exceptional cases.
Declaring the string isn't a bad thing in there, but its not doing anything other than holding another reference.
You can safely return from a try block. But as Damokles states, you should also have another return else where.
The general structure of exception handling is the following:
try
{
//do struff here
}
catch (...)
{
//handle exception here
}
finally
{
//clean up here
}
There are a couple of things to note in your code that are not entirely right (they are terrible in fact :p):
Only catch exceptions you are ready to handle and do not handle those you are not. This means that you should only catch particular exceptions (FileNotFoundException, ArgumentOutOfRangeException, whatever) that you know can happen in exceptional cases (never use exception handling as a normal execution flow tool). Catching System.Exception is considered bad practice (unless it is for logging purposes and you throw; immeadiately afterwards) because this exception can be thrown by any darn thing, which with all probability you have not foreseen when writing your code and therefore have no clue on how to handle it correctly.
Depending on your situation you should consider using finally blocks in order to clean up whatever you can before exiting the method (be it because of normal execution flow, or an unhandled exception). Note that finally blocks will be (normally) always executed before exiting the method scope.
Do not swallow exceptions and the information they contain. You should consider logging it somewhere (myApplication.log file) and show the user a more friendly "we have aproblem" message. Otherwise the only information you will have when bugs crop up in production will be whatever you show the user. All the valuable information stored in the caught exception will be lost.
There is no need to add exception handler in all the functions. Add the exception handling at the main() which wraps all the functions. Only add exceptions handlers at place where you intend to do some specific exception handling operation to prevent the application from crash.
Return value can be added in the try block.
I assume you are doing this to IGNORE exceptions? In that case you can do it like this:
try
{
// code
}
catch {}
This will catch all exceptions and do nothing with them(ignore).
I would however not recommend doing that, because you will now never know why some functionality in your system is not working as expected because no errors are thrown. I would then recommend at the minimum at least LOG the exception so that you can troubleshoot problems later. A better approach would be to log the exception and re-throw it and then have friendly exception handling at the UI layer.
This is considered a bad practice as you basically ignore the exception. You don't even show it to the user!
It's even double bad, because it is also a bad practice to copy-paste the same lines all over your code.
Recommended usage is to either handle the exception, or do not touch it at all. As it's rather uncommon that the code knows how to handle an exception, the common case is to not catch it at all!
Of course, way up in your main loop, you'll have a try-catch, which will log the exception and/or report the exception to the user.
With respect to your second question: Yes, a return statement can be part of the catch block. But if you don't know what to return, you should not catch the exception!
You should only catch exceptions that you are expecting and know how to handle them. by catch (Exception) you are catching all kind of exceptions in a method is not a good practice.
You can catch all exceptions to just log them or restart you application on fail..
For example
try
{
//My code which may raise an error.
}
catch (FileNotFoundException)//you are expecting this exception
{
//handle file not found here.
}
catch (Exception ee)
{
string message = ee.Message;
Log(message);
throw;//rethrow the exception
}

usage of try catch

Which is best: Code Snippet 1 or Code Snippet 2 ? And Why?
/* Code Snippet 1
*
* Write try-catch in function definition
*/
void Main(string[] args)
{
AddMe();
}
void AddMe()
{
try
{
// Do operations...
}
catch(Exception e)
{
}
}
/* Code Snippet 2
*
* Write try-catch where we call the function.
*/
void Main(string[] args)
{
try
{
AddMe();
}
catch (Exception e)
{
}
}
void AddMe()
{
// Do operations...
}
The real question to ask is "What is AddMe's contract to the rest of the world?" If AddMe represents the be-all do-all of an interface and correctly handles any exception that encounters in the appropriate way, then sure - let it catch it. If AddMe doesn't or can't know what to do with an exception, then it should throw and defer the handling to the calling code.
It depends, as usual.
In Snippet #1, the error handling is reusable. In Snippet #2, it is not, but that is better in cases where you want to use different error handling in different places.
Other than that, they are identical.
they will operate the same however Most would prefer to catch the logic inside the method if thats where it will be thrown from. Just a best practice though.
There's not best universal way. It depends on how you're going to handle your exceptions.
Do you plan on using a global logger in your main application? The you should have a try/catch block in your main method, and log exceptions there.
You can still try/catch in internal methods if you need to do other stuff with the exceptions, but remember to rethrow them, or else the logger in the main method won't have anything to log.
And remember, to rethrow correctly, use:
throw;
and not:
throw e;
Because the former keeps all the stack trace, while the latter doesn't.
IMHO, allow methods to throw exceptions. Don't attempt to hide when things go wrong. When they do it is up to the client to decide how they'd like to handle the exception. The reasoning for this is because each application may want to do something different with the exception.
TL,DR; Catch exceptions when you can do something about the exception, otherwise let them flow up the call stack until something else will handle them. If the exception cannot be handled by any particular part of your application, your application error event method should handle all the logging for you. Your logging functionality will be your final net for dealing with exceptions.
I've worked with a few shops that require try catch logic on EVERY method, and I learned that the Exception object does a better job watching your call stack than you can.
My other rule of thumb is notify the user of exceptions on user trigger events. So event based or command based captures would be a great place to catch, notify, then re-throw the same exception. (IE throw; NOT throw ex;)
There are already good answers to this question, coming ultimately down to "it depends", but I want to add a thought that I believe greatly influences which method is better for any given situation.
In your code snippet examples, but of your catches are catch (Exception e) {} as opposed to, say, catch (IOException e) or catch (NullReferenceException, or some other narrower exception type. The kind(s) of exception(s) you expect from the code in the try block will make a difference in the way you want to handle it. Especially if you have more than one type to consider, as could be the case if you handle exceptions outside of the subroutine - a large enough upper-level try block could have several different types of exceptions to handle, and start to run the risk of making the code messy.
My general rule of thumb, overall, is that if the exception is a non-critical error (especially if caused by invalid user input), I can handle it in the subroutine and keep the system running. On the other hand, if the exception means the program needs to close, I handle it higher up.

C# - Rethrow an exception without setting it to an variable

As all of you probably know, catching and re-throwing a exception in c# this way is evil, because it destroys the stack trace:
try
{
if(dummy)
throw new DummyException();
}
catch (DummyException ex)
{
throw ex;
}
The right way to re-throw an exception without loosing the stack trace is this:
try
{
if(dummy)
throw new DummyException();
}
catch (DummyException ex)
{
throw;
}
The only problem with this is that I get a lot of compilation warnings: "The variable 'ex' is declared but never used". If you have a lot of these, a useful warning may be hidden in the garbage. So, that's what I did:
try
{
if(dummy)
throw new DummyException();
}
catch (DummyException)
{
throw;
}
catch(AnotherException ex)
{
//handle it
}
This seems to work, but I'd like to know if there is any downside of re-throwing an exception that is not set to an variable. How does .net threats this?
Thanks in advance
Edit:
I've changed my code a little bit to make clearer what I wanted to do, as some had misunderstood
I'd like to know if there is any downside of re-throwing an exception that is not set to an variable.
No, there's no downside at all. A variable is only needed if you want to reference the exception in your code, but since you don't need to do that with a throw statement, you don't need a variable at all.
And you have exactly the right idea in attempting to eliminate "noisy" compiler warnings. They have a tendency to bury important errors that you do want to fix, and getting a clean build is always important. The best solution is simply to rewrite the code to use a parameterless catch clause.
However, be aware that in 82% of cases that I see*, it's a mistake to write code that uses throw at all. You generally shouldn't catch exceptions that you don't know how to handle and your only intended "handling" strategy is to rethrow them. There are cases where even using throw can reset the call stack, causing you to lose important debugging information. There are also better alternatives for logging exceptions to catching/rethrowing. You can find more information in the answers to these questions:
Main method code entirely inside try/catch: Is it bad practice?
what can lead throw to reset a callstack (I'm using "throw", not "throw ex")
There's absolutely nothing wrong with letting exceptions bubble up and handling them all in a central place. The rule to keep in mind is that you shouldn't use exceptions for flow control. But there's nothing wrong with throwing an exception in low level code, and showing the user an error message higher up the stack in UI code. Read Microsoft's Best Practices for Handling Exceptions for some general tips.
* Slightly more than the percent of statistics that are made up on the spot.
There is no downside to that. You are simply telling the compiler "I plan to catch this exception but I have no need for a reference to the actual exception", it doesn't affect how things are thrown or how exceptions work. Your latter example is the ideal way to do what you want, however if you are merely going to immediately throw; with nothing else whatsoever in the block, then why catch at all?
If you're not doing anything with DummyException in the catch block (which you can't, since you haven't given it an identifier), why not get rid of the try/catch block entirely? E.g., just do this:
throw new DummyException();
Although at that point, I'd probably evaluate what you're trying to accomplish here and rethink your application architecture so as not to not rely on exception propagation in this manner.
Why catch if your simply going to re-throw? Anyway, you may want to take a look at this previous discussion. Though not identical much of what is discussed is relevant:
Throw VS rethrow : same result?
Actually throwing an exception using "throw;" is a .Net best practice, because it preserves exception stack trace.
Throwing exceptions using "throw ex;" is considered a worst practice, because it looses the original stack trace and should be avoided.
Why catch and rethrow like this? Why do people always have to assume they know every case? Answer: Database transactions.
If you have a better way to do this please speak up Dr. Proton, no offense taken. Keep in mind that there are a lot of different database systems in use but most of them support transaction control (begin/commit/rollback) and have C# interfaces.
pseudocode (a simplified case):
try
{
db.beginTrans();
db.doStuff();
db.doOtherStuff();
db.commitTrans();
}
catch
{
db.rollbackTrans();
throw;
}
Now, it is quite annoying to lose the detail of whether doStuff() or doOtherStuff() failed and I don't see any good reason why C# would toss the line number information in this case. But it seems to. Hence the googling and my subsequent arrival. If I am missing something please do tell.

Why can't I write just a try with no catch or finally? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
Sometimes I do this and I've seen others doing it too:
VB:
Try
DontWannaCatchIt()
Catch
End Try
C#:
try
{
DontWannaCatchIt();
}
catch {}
I know I should catch every important exception that I'm expecting and do something about it, but sometimes it's not important to - or am I doing something wrong?
Is this usage of the try block incorrect, and the requirement of at least one catch or finally block an indication of it?
Update:
Now I understand the reason for this, and it's that I should at least comment on the empty catch block so others understand why it's empty. I should also catch only the exceptions I'm expecting.
Luckily for me I'm coding in VB so I can write it in just one catch:
Catch ex As Exception When TypeOf ex Is IOException _
OrElse TypeOf ex Is ArgumentException _
OrElse TypeOf ex Is NotSupportedException _
OrElse TypeOf ex Is SecurityException _
OrElse TypeOf ex Is UnauthorizedAccessException
'I don't actually care.
End Try
If you don't want to catch it, why are you using try in the first place?
A try statement means that you believe something can go wrong, and the catch says that you can adequately handle that which goes wrong.
So in your estimation:
try
{
//Something that can go wrong
}
catch
{
//An empty catch means I can handle whatever goes wrong. If a meteorite hits the
//datacenter, I can handle it.
}
That catch swallows any exceptions that happen. Are you that confident in your code that you can handle anything that goes wrong gracefully?
The best thing to do (for both yours and your maintenance programmer's sanity) is to explicitly state that which you can handle gracefully:
try
{
//Something that could throw MeteoriteHitDatacenterException
}
catch (MeteoriteHitDatacenterException ex)
{
//Please log when you're just catching something. Especially if the catch statement has side effects. Trust me.
ErrorLog.Log(ex, "Just logging so that I have something to check later on if this happens.")
}
No, you should not catch every important exception. It is okay to catch and ignore exceptions you don't care about, like an I/O error if there's nothing you can do to correct it and you don't want to bother reporting it to the user.
But you need to let exceptions like StackOverflowException and OutOfMemoryException propagate. Or, more commonly, NullReferenceException. These exceptions are typically errors that you did not anticipate, cannot recover from, should not recover from, and should not be suppressed.
If you want to ignore an exception then it is good to explicitly write an empty catch block in the code for that particular exception. This makes it clear exactly what exceptions you're ignoring. Ignoring exceptions very correctly is an opt-in procedure, not an opt-out one. Having an "ignore all exceptions" feature which can then be overridden to not ignore specific types would be a very bad language feature.
How do you know what types of exceptions are important and should not be caught? What if there are exceptions you don't know about? How do you know you won't end up suppressing important errors you're not familiar with?
try
{
}
// I don't care about exceptions.
catch
{
}
// Okay, well, except for system errors like out of memory or stack overflow.
// I need to let those propagate.
catch (SystemException exception)
{
// Unless this is an I/O exception, which I don't care about.
if (exception is IOException)
{
// Ignore.
}
else
{
throw;
}
}
// Or lock recursion exceptions, whatever those are... Probably shouldn't hide those.
catch (LockRecursionException exception)
{
throw;
}
// Or, uh, what else? What am I missing?
catch (???)
{
}
No catch or finally is invalid. Empty catch or finally is valid. Empty catch means you don't care about exceptions, you just try to do something and it doesn't matter if it doesn't work, you just want to go on. Useful in cleanup functions for example.
Also if you haven't to do something about an error maybe you should specify what kind of exception the program has to ignore.
If you have to ignore every exception, I can't see why you can't use try/catch in this way.
It's usually a mistake. Exceptions signal, well, exceptional behavior; when an exception is thrown it should mean that something went wrong. So to continue normal program flow as if nothing went wrong is a way of hiding an error, a form of denial. Instead, think about how your code should handle the exceptional case, and write code to make that happen. An error that propagates because you've covered it up is much harder to debug than one that surfaces immediately.
It's not made easy for you to do because it's considered bad practice by the majority of developers.
What if someone later adds a method call to the body of DontWannaCatchIt() that does throw an exception worth catching, but it gets swallowed by your empty catch block? What if there are some exceptions that you actually would want to catch, but didn't realize it at the time?
If you absolutely must do this, try to be as specific as possible with the type of exception you're going to catch. If not, perhaps logging the exception is an option.
An error exists, has been thrown, and needs to go somewhere. Normal code flow has been aborted and the fan needs cleaned.
No catch block = indeterminate state. Where should the code go? What should it do?
An empty catch block = error handled by ignoring it.
Note: VBA has a vile "On Error Continue"...
The reason I've heard is that if your try fails for ANY reason, giving you control of the error response is highly preferable to giving the Framework control of it, i.e., yellow screen or error 500.
what if you write only code with try
try
{
int j =0;
5/j;
}
this would equivalent to write
int j =0;
5/j;
so writing try does not make any sense , it only increse your count of lines.
now if you write try with empty catch or finally , you are explicitley instructing runtime to behave differently.
so that' why i think empty try block is not possible.
Yes, it is incorrect. It's like goto: one per 100 KLoc is fine, but if you need many of these, you are doing it wrong.
Swallowing exceptions without any reactions is one of the worse things in error handling, and it should at least be explicit:
try
{
DontWannaCatchIt();
}
catch
{
// This exception is ignored based on Spec Ref. 7.2.a,
// the user gets a failure report from the actual results,
// and diagnostic details are available in the event log (as for every exception)
}
The further-away-look:
Error handling is an aspect: in some contexts, an error needs to be thrown and propagate up the call stack (e.g. you copy a file, copy fails).
Calling the same code in a different context might require the error to be tracked, but the operation to continue (e.g. Copying 100 files, with a log indicating which files failed).
Even in this case, an empty catch handler is wrong.
With most languages, there is no other direct implementation than to try+catch within the loop, and build the log in the catch handler. (You could build a mroe flexible mechanism, though: Have a per-call-thread handler that can either throw, or stow away the message. However, interaction with debugging tools suffers without direct language support.)
A sensible use case would be implementing a TryX() from a X(), but that would have to return the exception in question.

How can code in a "try...catch" block throw an unhandled exception?

I had an exception in some code today: "A [some exception] was unhandled."
However, this code was clearly inside the "try" block of a "try/catch" structure.
What am I missing here?
Update: It's C#
Update: Oh, forget it. It turns out the specific mechanism of error is that I'm an idiot. There's no fix for this.
Does the catch statement specify a specific type of exception?
If it does, it will only catch that type of exception.
Were you running in a debugger with "break on exceptions"/"break on thrown" switched on? In this case you'll see the exception before it is passed to the try/catch.
Unmanaged exceptions will not be caught by catch(Exception e),you can try a
try
{
}
catch
{
}
instead of
try
{
}
catch (Exception e)
{
}
some problems caused by Recursion such as StackOverFlow exceptions and the like will throw inside of try...catch blocks because they are not actually thrown from any particular line of code within the block, but rather by the CLR. This is also true for Memory out of range exceptions and other problems that aren't the direct result of any one line of code.
Maybe you're talking about something like this:
I have 10 dollars that says its a ThreadAbortException or some other self-throwing exception. If that is the case you must catch the exception twice.
Without knowing the language it's difficult to say, but many languages have the concept of exceptions that cannot be caught - for example in .NET, OutOfMemoryException and ExecutionEngineException (amongst others) cannot be caught, since they are essentially non-recoverable.

Categories

Resources