2

I am trying to catch an exception using a try-catch-finally block. i have caught the exception in the catch block and passed it to the finally block using a global exception variable. Doing so, i have handled the exception scenario in the finally block. I know this sounds wierd, but theres a need to do so. Please let me know if there is any coding standard issue with the same. Also if you can suggest something on the same, i will be really obliged.

Thanks.

Jakob Möllås
  • 4,239
  • 3
  • 33
  • 61
user756825
  • 41
  • 3

2 Answers2

4

catch is to catch the exception and do any necessary exception handling. The finally block is there to clean up any left open resources, like file handles, database connections, etc. This block will most of the time run and therefore is the correct place to do cleanup, but no the handle the exceptions themselves, those should be dealt with in the catch block.

Tony The Lion
  • 61,704
  • 67
  • 242
  • 415
2

The try-catch-finally pattern is a very useful and powerful pattern, if used as intended. Handling exceptions in the finally block is not recommended and does not make much (any?) sense.
Try to reorganize your code to fit the pattern, not the other way around.

Small example:

var reader = new StreamReader(path);
try
{
   // Do your work here
   reader.ReadToEnd();
}
catch (IOException ex)
{
    // Handle specific error here
    ShowUserError(ex.Message);
}
catch (Exception ex)
{
    // Handle general error here
    LogError(ex);
}
finally
{
   // Perform clean up here
   // This code will run regardless if there was an error or not
   reader.Close();
}

Also, have a look at the MSDN documentation for Try...Catch...Finally Statements.

Jakob Möllås
  • 4,239
  • 3
  • 33
  • 61