Reputation: 67213
I have seen code like this (actually seeing another person type it up):
catch (Exception ex)
{
string exception = ex.ToString();
}
Is this code bad? If so, why? There is an appropriate "chain of catch handlers (eg more specific one above, filtering down to general catch all Exception, but in the string conversion of the Exception, I guess you are converting a lot more than is probably needed, to a string (All you really need is the InnerMessage or one of the other string properties depending on the scenario). Any thing else wrong with this code?
I have also seen devs put breakpoints on every line of code. What is the point of this? Why not just put one at the top and then use "run to cursor" (love that feature)?
Finally, what's the advantage of using break on all exceptions in Visual Studio?
Upvotes: 0
Views: 284
Reputation: 96702
I just used "break on all exceptions" yesterday.
I was chasing down a pretty obscure bug (in fact, the code was working perfectly, which is the hardest kind of bug of all to find), and while my C# code was executing an apparently-malfunctioning IronPython script, I kept getting ArgumentException
messages appearing in the console.
It turns out that this IronPython code:
try:
value += x
except ValueError:
pass
results in an ArgumentException
being thrown, and handled, inside the IronPython runtime.
Also, if you have "break on all exceptions" turned on, VS actually breaks on that value += x
line, calls up the Python source, lets you inspect local values, etc. Pretty nice. Anyway, now when I see those exception messages show up in the console I no longer worry that I'm ignoring something that's going to bite me.
Upvotes: 0
Reputation: 45117
This developer might not know that you can catch all (managed) exceptions like this ...
try
{
// do something
}
catch( Exception )
{
}
And not suffer the compiler warning of a catch block like this ...
catch( Exception ex )
{
// don't use ex
}
Also, he might not know about the $exception pseudo-register.
Upvotes: 2
Reputation: 26426
This looks like a lazy programmer who:
Upvotes: 3
Reputation: 13972
string exception = ex.ToString();
That doesn't DO anything. Better to log it or use MessageBox.Show(...);.
Breakpoints on each line ... not much point - use run to cursor or step over/step in.
Break on all exceptions: I've actually used. I've had exceptions fail quietly that were "handled" by some library silently. Break on all helped me track that down. Additionally "Break on all" can help you make sure you're only getting exceptions you expect (Also helped by not catching a generic "Exception" class but only catching the particular exception.
Upvotes: 3
Reputation: 161773
The only value of the code you posted would be to permit the full exception to be visible while in the debugger. It's not necessary, since the debugger will do that anyway, but maybe this code was there since before the debugger did that.
Upvotes: 2