Throw Exception Vs Throw New Exception

  • Thread starter Thread starter Kerri
  • Start date Start date
K

Kerri

Hi,

I am new to .NET

In my Error Logic on my Aspx pages when an error happens
it hits my catch statement where I throw an Exception.

My question is :

what is the difference between Thwo Exception and Throw
New Exception?

Anq when should either be used?

Thanks,
Kerri.
 
If you are not going to enclose the thrown exception inside of another
exception, you can just throw the exception that was caught.

Otherwise you can create a new exception and pass in the throw exception as
the InnerException if you wish to do so.

It is more up to how your organization is standardizing these types of
conditions, not which is the "always right" way to do it.

Throwing a new exception that is no different than the old exception just
adds one more class for the garbage collector to take care of.

Joe Feser
 
Kerri,
In addition to Joe's comments, be careful with throwing an existing
exception in VB.NET. Your stack trace may be reset.

If I have:
Try
SomethingThatThrowsAnException()
Catch ex As Exception
' log the exception
Throw
End Try

When you simple use the Throw statement as I have, the stack trace will be
maintained from inside of SomethingThatThrowsAnException where the exception
really happened.

However if I had used:

Catch ex As Exception
' log the exception
Throw ex
End Try

The Stack Trace will be reset to this routine, loosing the fact that it
originally occurred inside of SomethingThatThrowsAnException.

Alternatively we can:
Catch ex As Exception
' log the exception
Throw New Exception(ex)
End Try

Which will create a new exception with a reference to the original
exception, as the inner exception.

Hope this helps
Jay
 
Hey thanks for the Tip, I was not aware of that.

I always wondered why VB allowed you to do that.

No I have about 200 places to fix that code. :)

Joe
 
Back
Top