Throw Statment

  • Thread starter Thread starter Pure Heart
  • Start date Start date
P

Pure Heart

Hi

for me the throw statment is very confusing and un clear, i mean for
structured error handeling if the eception is not handeled it will search for
handlers in the calling methods hirarchy so why we need to re throw the
exception to the calling method since it will be done autimatically by .NET ?

whats the use of throw then ?

thank you
--
Ammar S. Mitoori
IT Head QIMCO Co.
Tel : +9744831199
Mobile : +9745378400
Fax : +9744831643
 
If you just want the exception to bubble, then you are correct: you
don't need to do anything.

You only need to catch and re-throw the exception if you have something
worthwhile to do; for example:

try
{
// do something
}
catch
{
myObj.RollbackChanges(memento);
throw; // throw original exception
// preserving stacktrace
}

Alternatively, you might want to wrap the exception to provide more context:

try
{
// do something
}
catch (Exception ex)
{
throw new InvalidOperationException("Something went bang
while twinking the flibble", ex);
}

(which you might do for security reasons among others - sometimes
stripping the "inner" exception, sometimes not.

Marc
 
Basically, it is used for logging purposes. Consider the Example of Web
application.

UI Will call the Database Layer.
If an exception occurs at database level, although the function will catch
the exception for logging purposes
but it will also throw it again so that it can be handled at UI (may be
custom error screen).

For Ex:
void GetDataset()
{
try
{
CallDatabase()

}
catch(SQLException)
{
Log It();
throw;
}
}

Hope this helps.
 
Back
Top