views:

105

answers:

5

I am learnig CSharp.I have some doubts in handling exceptions.Kindly guide me to improve my coding knowledge.

Suppose i construct a code segment :

try { 

        SomeWork();  
        return success;
    }
    catch (someException ex)
    { 
        throw new ExceptionDetails(ex);
        return failure; 
    }
    catch(AnotherException exp)
    {
        throw new ExceptionDetails(exp);
        return failure;
    }
    finally
    {
        CleanUpStuff();
    }

Questions:

(1) Can i use return statement after "throw" (throwing exception) ?

(2) Is throwing an exception ugly practice?.When exactly do i need to throw an exception?Do i need to use "throw" to report only custom exception ?

(3)

    try
    {
        SomeWork();
    }
    catch(StringIndexOutOfBound ex)
    {
        throw;
    }

using anonymous throw statement inside catch is a good practice?

+3  A: 

Hint: anything after throw will never be executed. Compiler should tell you that!

Daniel Mošmondor
It also depends on why you are logging, we use the TraceListener and Trace.WriteLine to do our error logging (as our system is a real-time remote system, so our operators want to be able to see what errors crop up). I guess what I'm trying to say is only throw anonymous exceptions if you are unable to deal with the exception at the lower level.Also, on a completely different topic, if you are not going to use the exception you catch there is no point in naming it. catch(Exception) will work just as well as catch(Exception ex) if yo don't intend to use ex
Tim Joseph
+1  A: 

Whan you throw an exception your return statement won't work.

Try to catch the specific exception and handle it from there itself and also return the value after the finally block.

throw ex

will reset the stack trace to the point of the throw.

throw

will maintain the original stack which will be helpful when debugging.

rahul
You've got the `throw` and `throw ex` backwards. `throw` will maintain the original stack trace while `throw ex` will break it.
Scott Dorman
+1  A: 

In regards to 3- read about the differences between throw and throw ex. As Daniel says the compiler will tell you about unreachable code.

RichardOD
+3  A: 

1) A thrown exception (if not handled) will automatically return to the previous method so there is no need to return. In fact, the compiler should warn you that there is unreachable code.

2) Throwing exceptions is not ugly as long as you do it for ... exceptional circumstances. Your coding should be defensive enough that you don't rely on exceptions for normal program flow.

3) Don't do #3 if you're not going to be doing anything else with the exception. If you are going to be logging it or doing something meaningful and would still like to rethrow the exception, then use it "anonymously" (??) as you have there.

rein
Regarding #2, exceptions should be used for **error** conditions not exceptional circumstances.
Scott Dorman
Scott, sometimes you reach situations in your code which aren't technically errors but they are undesirable or irrevocable conditions. Under these circumstances exceptions need to be thrown - they are not errors, they are circumstances that are the exception. Examples: parameter validation checks, null checks, string length checks, credit card validation checks. These aren't technical errors - they are just circumstances where you can't possibly use code to correct the situation.
rein
+1  A: 

1) Having a return statement after a thrown Exception will not compile and you should get an Unreachable code warning.

2) Throwing an exception is perfectly valid, this potentially allows for some more generic error handling to occur. e.g.

public void readFile()
{
    try
    {
        // Perform IO action
    }
    catch ( FileNotFoundException ex )
    {
        // Perform error recovery e.g. create a default file   
    }
    catch ( Exception ex )
    {
        // Cant perform any error recovery at this level so throw the exception to allow the calling code to deal with it
        throw;
    }
 }

You could argue here that you should be testing to see if the File exists before perforrming the IO action. As a rule of thumb if you can test for something with an if statement, then you should do so. You can generally catch specific exceptions when you know you can recover from them within the scope that they are generated.

This sort of question really depends on the situation as testing before carring out an action could be a better course of action. You will get more of a feel for what is required with practice!

3) As has been mentioned elsewhere in the post, it is generally a good idea not to just 'throw' an exception as having information about how and where it occurred is often very useful in debugging.

TK
Please change your throw ex; to throw;
rein
why is it necessary to change the code snippit?
TK
Well firstly, you shouldn't be "doing error handling wherever you can". You should only do error handling where you want to do something with the error. Your code snippet shouldn't catch Exception because you're not doing anything with it. You are correctly doing something with FileNotFoundException. Also, if you rethrow an exception you should never throw it using "throw ex;". Changing the code snippet will make your answer more correct.
rein
duly noted! Code snippit changed
TK
Isn't that catch ( Exception ex ) block redundant? The exception's just going to bubble to the next higher level if you don't catch it anyway... Microsoft specifically tells you not to do this: http://msdn.microsoft.com/en-us/library/ms229005.aspx
R. Bemrose
You are of course correct! However, there are occasions where this might be a valid thing to do, e.g. you need to log the exception etc. Even then it is possible to argue that this behaviour could be done in a more generic fashion.
TK