Thursday, December 22, 2011

Best Practices: Exception handling Myth #1

MYTH#1 DO NOT SIMPLY RETHROW A CAUGHT EXCEPTION

Rethrowing the same Exception is an “Exception Handling” method.

In the catch block, there must be some work to handle the Exception.

[VB]

Try

  ‘ Do some code

Catch ex as Exception

  Throw ex

End Try

[CS]

try

{

  // Do some code

}

catch(Exception ex)

{

  throw ex;

}

This will suppress the actual line where the error was thrown and it will show the rethrown line as the actual source of exception.

 

For rethrowing the exception, you can simply create a new Exception with the caught exception as Inner Exception.

[VB]

Try

  ‘ Do some code

Catch ex as Exception

  Throw New Exception(“Process Failed”, ex)

End Try

[CS]

try

{

  // Do some code

}

catch(Exception ex)

{

  throw new Exception(“Process Failed”, ex);

}

No comments:

Post a Comment