How much do I use try/catch statement in my code?

G

Guest

I try to insert try/catch statement in every single method of my c# code
to prevent the app from crashing not nicely.
Do you think it is good idea?
I remember that an artical says " do not overuse try/catch " but I don't
remember the reason why I should overuser.
I don't see the reason I should not overuse them.
What's your opinion on it?

Thx
 
J

John Vottero

Back 9 said:
I try to insert try/catch statement in every single method of my c# code
to prevent the app from crashing not nicely.
Do you think it is good idea?
I remember that an artical says " do not overuse try/catch " but I don't
remember the reason why I should overuser.
I don't see the reason I should not overuse them.
What's your opinion on it?

Don't insert a try/catch unless you have something useful to do in the
catch.

If you just want to make sure that all exceptions are handled (logged etc.)
then use:

System.Windows.Forms.Application.ThreadException event

and/or

System.AppDomain.UnhandledException event
 
G

Guest

Do I get the reason why ?
Is there any overload for using them or something?

Thank you for your reply.
 
J

John Vottero

Back 9 said:
Do I get the reason why ?

The reason is just to keep the code easy to read and understand. And, if
you want to have a common exception handler, the ThreadException and
UnhandledException events are a lot easier than adding a try/catch to every
method and property that you have.
Is there any overload for using them or something?

There is almost no overhead with a try/catch block. There is a little
overhead if you actually throw an exception but, it's not much. Even the
overhead of a throw is insignificant as long as the "normal" code path
doesn't throw any exceptions. If you find that your code is throwing
thousands of exceptions per second, you may want to rethink your design but,
running through thousands (or millions) of try/catch blocks per second is
fine.
 
J

Jon Skeet [C# MVP]

Back 9 said:
I try to insert try/catch statement in every single method of my c# code
to prevent the app from crashing not nicely.

If one method fails deep in the stack, how do you expect the rest of
the app to recover?

So long as at the root of the stack you have an appropriate try/catch,
it won't crash.
Do you think it is good idea?

Absolutely not. One of the great things about exceptions is the way
they bubble up the stack. If you're going to put a try/catch in every
method, you're basically returning to the bad old days of return codes
indicating success/failure and manual checking.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top