0

I have been using exception handling for some time and have installed Resharper and now getting all sorts of messages saying I should and should be doing this. Anyway, it says I shouldn't be using try and catch blocks around my code. So where do I put them to catch exceptions? I have seen people looking for certain exceptions like File not found, but what about all the other errors or exceptions that are unique?

Here's an example of some exception handling it moans about:

try
{
    var rnd = new Random();
    var buffer = new byte[sizeof(UInt64)];
    rnd.NextBytes(buffer);
}
catch (Exception)
{
    throw;
}

Does anyone have links for best practices for exception handling that would keep re-sharper happy?

Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100
Funky
  • 12,890
  • 35
  • 106
  • 161
  • 8
    You put them in to catch exceptions that you can do something about. You're not doing anything about any exception here; you're just catching it, doing nothing with it, and throwing it again. The exception is *already* going to be the caller's problem if you do nothing; you don't need to actually write code that does what the runtime is going to do automatically. – Eric Lippert Aug 28 '13 at 16:02
  • 3
    Also, read this before you write any more exception handling code: http://ericlippert.com/2008/09/10/vexing-exceptions/ – Eric Lippert Aug 28 '13 at 16:11
  • 1
    And this question, though a poor fit for SO, has a lot of good suggestions: http://stackoverflow.com/questions/2883936/common-programming-mistakes-in-net-when-handling-exceptions/2884340#2884340 – Eric Lippert Aug 28 '13 at 16:12
  • @EricLippert I want to +10 on your comments for this, especially the first one. – Mark Schultheiss Aug 28 '13 at 16:15

2 Answers2

0

Only catch those exception which you can handle, like insertion of duplicate primary key, So that you can show the user a message to enter different values.

For other exception let them bubble up in your library and handle them in one place. Like Application_Error event in ASP.Net

user2711965
  • 1,795
  • 2
  • 14
  • 34
0

As pointed out by others already, only use try/catch if you actually plan to do something about the exception inside the catch block - doing so keep in mind that there is actually no guarantee that the catch block will actually execute (e.g. a power failure).

See explanation that was given to me when I asked a quite similar question: when to use try/catch

If you only wish to diagnose/log an exception and don't do anything specific about it, you can use a global exception handler, i.e. AppDomain.UnhandledException - this way you can centralize handling.

Community
  • 1
  • 1
w128
  • 4,680
  • 7
  • 42
  • 65