Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Why throw a new exception rather than the one caught?

Status
Not open for further replies.

andegre

MIS
Oct 20, 2005
275
0
0
US

This article talks about throwing exceptions, but my question is why do they say to throw a new exception, of the same type, but with a different title(?)?

Why not just say:
Code:
catch (Exception ex)
{
   throw;
}

as opposed to:
Code:
catch (Exception ex)
{
    throw new Exception("my repetitive exception", ex);
}

Just curious...
 
you can use the new error to create a friendly error message for the end user and log the actual error some place else. I would take it one step farther though, and create a another subtype from Exception.
Code:
class FriendlyUserException : Exception
{
   public FriendlyUserException(string message, Exception actual)
   : base(message, actual)
}
Code:
try
{
   ...
}
catch(Exception e)
{
   throw new FriendlyUserException("Ouch, something went wrong.", e);
}

Jason Meckley
Programmer

faq855-7190
faq732-7259
 
To expand on jmeckly's answer, I often use custom exceptions that contain more details about the context the exception occurred in, so storing things like repository names/connection strings, current user, etc so that when they are caught, there's more infomation available to help you.


----------------------------------------------
Ben O'Hara
David W. Fenton said:
We could be confused in exactly the same way, but confusion might be like Nulls, and not comparable.
 
oharab, do you just output that information in a big string, or a datatable? That's a great idea but I'm trying to figure out how to make it work with our exception handling system.

We just write all of our exceptions to a table, and only save the message, stack trace, additional info, machine name, user....that's about it. I guess I could expand the message field and have that contain much more info after the regular message.
 
Depends what I'm doing & what logging is in place.
Generally I use log4net so I can change my logging needs on the fly.
Some systems log errors into a database, some just write everything to a text file, others email me when fatal errors occur. Using log4net lets me set these options as needed, so I only turn debug logging on when there's an issue I'm trying to fix, etc.




----------------------------------------------
Ben O'Hara
David W. Fenton said:
We could be confused in exactly the same way, but confusion might be like Nulls, and not comparable.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top