12

My senior colleague tells me to wrap every method within a try-catch block so they can trace where exceptions occurs to help debug issues quicker. Is it better to wrap every method in a Try Catch such as this to:

Public int foo()
{
   try
   {
       //do something
   }catch(Exeception ex)
   {
       //do something with ex
   }
}

Or is it better to catch exceptions where I think they may occur? E.g. doing something with an array may cause the IndexOutOfRangeException will occur.

//wrap this in try catch
    int[] array = new int[3];

                array[0] = 1;
                array[1] = 2;
                array[2] = 3;
                array[3] = 4;

Thanks.

Harry
  • 3,031
  • 7
  • 42
  • 67
  • 11
    "E.g. doing something with an array may cause the IndexOutOfRangeException will occur." - only if you've got a bug. Don't try to catch specific exceptions that are due to bugs - you *want* them to fail, get logged, then get fixed. – Jon Skeet Sep 04 '15 at 09:30
  • 10
    And no, you *definitely* don't want to wrap every method call with a try/catch block. "So they can trace where exceptions occur" - that's what the stack trace is for... – Jon Skeet Sep 04 '15 at 09:31
  • Thanks Jon, but can you expand a little on "you want them to fail, get logged, then get fixed." how do you log them without catching them in a try catch? – Harry Sep 04 '15 at 09:34
  • 4
    You catch them in a top-level try/catch, for the whole program (or request, or user action, or whatever it is). But you *don't* litter your whole codebase with try/catch. – Jon Skeet Sep 04 '15 at 09:35
  • I see, is it possible to provide an example of this approach or resource @JonSkeet – Harry Sep 04 '15 at 09:37
  • 2
    Points for trying to understand your senior and checking this for yourself. – Myrtle Sep 04 '15 at 09:38
  • Well we don't know what kind of app you're writing, which makes it hard to give an example - Robert Kirk's answer gives an example for Windows Forms. – Jon Skeet Sep 04 '15 at 09:41
  • wrapping all your code in try catch may give you some performance issues if they throw exceptions. – Rohit Sep 04 '15 at 09:43
  • This approach I mentioned is used for both ASP.NET and Windows Forms. @JonSkeet – Harry Sep 04 '15 at 09:43
  • Well in ASP.NET you set an error handler, which should do whatever you want to happen if an exception bubbles up to the top request handler. – Jon Skeet Sep 04 '15 at 09:44
  • ah I see, I shall look into this further. Thanks @JonSkeet – Harry Sep 04 '15 at 09:45

5 Answers5

14

The try block contains the guarded code that may cause the exception. The block is executed until an exception is thrown or it is completed successfully.

You can have a look on How often should I use try and catch

The basic rule of thumb for catching exceptions is to catch exceptions if and only if you have a meaningful way of handling them.

Don't catch an exception if you're only going to log the exception and throw it up the stack. It serves no meaning and clutters code.

Do catch an exception when you are expecting a failure in a specific part of your code, and if you have a fallback for it.

Of course you always have the case of checked exceptions which require you to use try/catch blocks, in which case you have no other choice. Even with a checked exception, make sure you log properly and handle as cleanly as possible.

Community
  • 1
  • 1
Mohit S
  • 13,723
  • 6
  • 34
  • 69
  • Thanks, can you expand on this a little "when you are expecting a failure". – Harry Sep 04 '15 at 09:56
  • 3
    For example, you try to send an email using a primary SMTP server, which throws an exception because it times out, so then you catch the exception and try using an alternative fallback SMTP server. – Loathing Sep 04 '15 at 09:59
  • 1
    @Mohit "Don't catch an exception if you're only going to log the exception and throw it up the stack"- But what if you want to log every exception? That's what I'm trying to deal with now, I need to log everything, but not sure how if I don't wrap it in a try catch especially since there are many threads, which means they won't get thrown up to the main thread. – Goku Nov 11 '19 at 16:46
  • But, if I catach it and throw it up the stack, eventually my parent function will log it in a log file. That is worth doing? At the moment I am not rethrowing and logging exceptions inside each method. So the user is not being informed to view the log because the errors occurred in nested function calls. – Andrew Truckle Jan 14 '22 at 14:26
1

Better to use it in critical parts of your code and then:

[STAThread]
static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
    AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
    ServerForm form = new ServerForm();
    Application.Run(form);
}
static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
    MessageBox.Show(e.Exception.Message, Program.Name);
}

static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
    MessageBox.Show((e.ExceptionObject as Exception).Message, Program.Name);
}

just in case of unhandled Exception

0

There is no problem in using Try catch block as it has no overhead (unless if you keep adding it everywhere which might include overhead in readability) while there is often additional IL added for catch and finally blocks,when no exception is thrown there is little difference in behaviour.

However if your code does throw an exception this is where you have a slight performance issue as in such cases an exception must be created,stack crawl marks must be placed and, if the exception is handled and its StackTrace property accessed, a stack walk is incurred. so as a result it might not be good idea to always wrap your code in try catch block alternatively you can place it at a parent level and then inspect the stack trace

Rohit
  • 10,056
  • 7
  • 50
  • 82
0

Using try-catch depends strongly on the context. For me there's no rules to tell developer when using or not a try catch block.

Developer code must prevent the evident errors or exceptions due to context like null parameters or file existence or the data coherency. In case of developing a library used by many other programs, the library catches only some critical exception to allow top level programs have more details about errors and exceptions.

For example, we have a method in library using System.IO.File.WriteAllLines.

void bool DoSomethingWithFile()
{
  try
  {
     // Some code here
     System.IO.File.WriteAllLines()
     //some code here
     return true;
  }
  catch()
  {
     LogExeption();
     return false;
  }
}

How to tell top level program that the PathTooLongException or there's a security exception unless you add throw in the catch block.

S. Gmiden
  • 147
  • 5
-4

Every piece of code where you think an error may occur should be wraped inside try catch block. If you are working on some real time problems and applications you should use it everywhere. It is a good programing practice. If you don't know what exception could occur, just use catch block for general exceptions:

try
{
   //your code
}
catch (Exception ex)
{
   //exception handling
}

Or you could use:

try
{
   //your code
}
catch
{
   //your custom message
}
  • 1
    in the second case, you hava a error and don't even notice it – fubo Sep 04 '15 at 09:40
  • 2
    I strongly disagree with this approach. try/catch should usually be used sparingly - you should only catch an exception if either a) you can genuinely handle it (e.g. retrying) or b) it's at a "top level" for the application (e.g. the top level request handler for a server) and you're basically just stopping the whole application from stopping. Everywhere else, allow the exception to bubble up. – Jon Skeet Sep 04 '15 at 09:43
  • These two are for general exception handling, it should be the last catch block if you have multiple catch blocks. One thing to notice is you can't use both of these, just one, because it will throw a syntax error. And the last one you can't see the error that occured, it just knows that it occured and it will show your own custom message... – Goran Rojovic Sep 04 '15 at 09:44
  • 2
    Why would you not want to *at least* log the exception? I can't remember the last time I used a "blank" catch block like this. – Jon Skeet Sep 04 '15 at 09:49
  • what if you have a multiple catch blocks, let's say catch block for ArgumenNullException, IndexOutOfBoundsException etc, and an error occurs that you didn't handle in your catch blocks... your app will crash... general catch block should be the last catch block, and it will ensure that an error that you didn't handle doesn't crash your application... – Goran Rojovic Sep 04 '15 at 09:58
  • Is this not overkill? – Harry Sep 04 '15 at 10:16