views:

106

answers:

5

Is it correct to catch each exception with Exception class ??? If not then what should be the correct sequence to catch exception within try catch block?

e.g

try{
       .
       .
       some code
       .
   }
   catch(Exception ex)
   {
       throw ex;
   }
+5  A: 

No, this is wrong.

  1. Catching only to throw again is pointless.

  2. It's rethrowing incorrectly, which leads to losing the stack trace. The right way to rethrow (when rethrowing makes sense, that is), is simply: throw;

  3. If you want to catch one exception and then throw another, you should keep the first one as an inner exception of the second. This is done by passing it in to the constructor.

Bottom line: Only catch the exceptions that you know what to do with.

Steven Sudit
+1 for `throw;`
SLaks
+100 for `throw;` (or, so I would like to award)
Mike Caron
while I agree on in general `throw;`, that is not what he is asking.
liho1eye
@liho: It's not what he asked about, but it's one of the things he needs to know. I believe that, in total, my answer addresses his question.
Steven Sudit
Ok, I'll bite: What part of my answer is so wrong that I deserve a downvote? Or is this just more strategy?
Steven Sudit
A: 

Always catch most specific exceptions first.

    try
    {
        // some file system code
    }
    catch (DirectoryNotFoundException e1)
    {
        // do something about it
    }
    catch (IOException e2)
    {
        // do something else about it
    }
    catch (Exception e)
    {
        // most generic catch - probably just dump onto screen or error log
    }

Rethrowing is made for easier debugging - that is not a way to tell user about the error. The right way to do it:

    try
    {
        // some code that does X
    }
    catch (Exception e)
    {
        throw new Exception("describe X and parameters to it where applicable", e);
    }
liho1eye
+2  A: 

In my opinion, you should generally try and catch exceptions that you would expect to come out of the code you call in the try block, and let the rest get caught elsewhere. For instance:

try
{
    // ...  some code that you know may throw ArgumentException or any other known exceptions
}
catch (ArgumentException ex)
{
    // ... handle the exception with a good idea of why it was thrown
}

In the catch block, you now can handle the error in a clean, specific way knowing that an invalid argument was passed somewhere in the try block. For example, you could alert the user that they have supplied an invalid argument.

If something happened that you didn't expect (e.g. a NullReferenceException) you probably don't know how to recover from it, so by not catching it you delegate responsibility to the consumer of your component to handle exceptional situations in general.

In short, you should catch exceptions when you know how to handle or correct the error, and allow unknown errors to be caught higher-up the call chain

Make sense?

jscharf
+1  A: 

It's not so much that it's incorrect, as that re-throwing the exception is not what you should be doing. There's a host of reasons that re-throwing it is bad mojo and they touch things like maintainability, performance and good coding practices. Unfortunately, the compiler allows it.

As for when you should be catching the exception,a good rule of thumb is that the exception needs to be caught at the point that you want your code to HANDLE the exception.

Stephen Wrighton
+3  A: 

If you are throwing the exception right after you catch it -- that is essentially the same as not having a try / catch block at all.

Catch specific exceptions that might occur.

For instance, you try to save a file but for some reason it cannot be written:

    try
    {
      SaveFile();
    }
    catch(FileIsReadOnlyException)
    {
      //do whatever to recover
    }
    catch(Exception ex)
    {
      //If we hit the generic exception, we're saying that we basically have 
      //no idea what went wrong, other than the save failed.
      //
      //Depending on the situation you might want to sink and log it, i.e. do nothing
      //but log it so you can debug and figure out what specific exception handler to
      //add to your code -- or you might want to try to save to a temporary file and
      //exit the program.
      //
      //If you were UpdatingAnAdvertisement() or doing something else non-critical
      //to the functioning of the program, you might just let it continue and
      //do nothing.
      //
      //In that case, you can just omit the generic catch.
    }
Timothy Lee Russell