When should I throw an Exception

  • Thread starter Thread starter Mr Newbie
  • Start date Start date
M

Mr Newbie

When you write code, you can generally structure it so that you handle all
the errors, so when is it most appropriate to Throw an exception rather than
coding for error handling in a more granular sense.
 
Ive just read a lot on this and there is guidence, principly if something
does not do what it is intended to do then this should be regarded as a
system failure and an exception should be thrown.
 
But more granularly, you should only throw an exception when something
exceptional happens :)

As a general rule, in each routine I write I try to catch and handle only
the exceptions that I can actually do something about in that routine. If it
is an exception that is thrown because of something that is clearly outside
the scope of that exact routine then I either just let the exception bubble
upwards, or sometimes I catch it, log it, and then rethorw it (using only
the Throw function) being careful to preserve the stack.

Try

DoSomehtingHere()

Catch ex As SpecificException
HandleTheSpecificExpetion()

Catch ex As Exception
LogTheException()
Throw 'rethrow the exception upwards and preserve the call stack (DO NOT
USE 'Throw ex' here)

Finally
DoMyCleanUpHere()

End Try
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top