Need advice on try catch blocks in c#

Hi Experts,

I have web application with 8 buttons  and each button has different functionality and am  using try {} catch {} blocks in each button click event.

1)Can I use  try,catch blocks  this many times in a page ? Is this best practice?

2)Is there any differnce between below 2 statements?

a)Class1 obj;
obj=new Class1();

b)Class2 obj=new Class2();

Thanks in advance
Who is Participating?
Shaun KlineConnect With a Mentor Lead Software EngineerCommented:
You can use as many Try/Catch/Finally blocks as you need, including having nested levels. A best practice is to use Try/Catch blocks where ever you need to process an known exception (such as trying to write to a file that is open by another process).

Technically, there is no difference between your two statements, in that after the last line of each example you will have a created and instantiated object. However, the first example provides more control, in that you can delay the instantiation until you need it.
Raheman M. AbdulConnect With a Mentor Senior Infrastructure Support Analyst & Systems DeveloperCommented:
1. If the exception you are catching are different then you can use as many times but in my view this does not effect.

2. There is no difference.
Kalpesh ChhatralaSoftware ConsultantCommented:
1. you can use Try Catch as per your requirement. if possible write exception in some file or database. so you can trace it easily.
try this tool for Error logging ;

2. No difference.
ksd123Author Commented:
Thank you all.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.