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?
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.