Link to home
Start Free TrialLog in
Avatar of ToolTimeGang
ToolTimeGangFlag for United States of America

asked on

Visual Basic and how to throw exceptions

I am recompiling vb code from vs2003 to vs2010.
One of the warnings is telling me not to "throw new exception".
so I changed it to a more specific to the situation like "throw new FormatException".
 
But through my research, I could see some blogs that advise you also never to use ApplicationException.  would that also be because it is too general?  or is there another reason why you shouldn't use that type of exception?  

thanks for helping me!
Avatar of kaufmed
kaufmed
Flag of United States of America image

According to http://msdn.microsoft.com/en-us/library/system.applicationexception(v=vs.110).aspx:

If you are designing an application that needs to create its own exceptions, you should derive custom exceptions from the Exception class. It was originally thought that custom exceptions should derive from the ApplicationException class; however in practice this has not been found to add significant value.

So...

would that also be because it is too general?

...I would say yes.

You might also condsider the article referenced by that documentation:  Best Practices for Handling Exceptions.
ASKER CERTIFIED SOLUTION
Avatar of Jacques Bourgeois (James Burger)
Jacques Bourgeois (James Burger)
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ToolTimeGang

ASKER

Thank you.  This was helpful!
This way, the receiver of the exception has a better idea of where to look for a possible solution.
Defining a custom exception offers no more information on where the exception occurred versus using one of the existing exceptions. This is what the stack trace provides, which all Exceptions will have anyway.

As mentioned in the article I referenced above, creating your own new exception type allows the programmer to take programmatic action based on the type of exception being raised. For example, you can easily recover from a FormatException (when trying to convert strings to other types), but encountering a SqlException when your program is trying to retrieve configuration settings from a database, then you probably cannot continue execution. If you're not going to be taking any programmatic action (e.g. try/catch, logging, etc.) based on what kind of exception occurred, then it is extraneous to create a new exception type.