James Ray Anderson

James Ray Anderson
James Ray Anderson
0 comments

Exceptions - Part II - Throwing Exceptions

8:59 PM
Overview
In Part I we talked about exceptions and how they happen and how to catch them.  This tutorial will talk about throwing exceptions and the conditions when to do them.

Throw Exceptions
There are situations where you want to throw an exception, such as:
  • Invalid parameter value
  • Method cannot complete as desired
  • Invalid object state
  • methods are not yet implemented
However, there are some situations that you should avoid throwing exceptions as it would violate some best practices, such as:
  • Returning an exception as a value or parameter
  • throwing exceptions in debug mod but not release mode
  • throwing system exceptions (System.Exception, System.SystemException, System.NullReferenceException, System.IndexOutOfRangeException)
  • Intentionally changing the flow of an application by using an Exception

Throwing Exceptions
ou can use the throw statement to raise an exception.  Usually you do this inside a Try or Catch block.  For example:
throw new FileNotFoundException(@"c:\temp\temp.txt not found",e);
Constructors
A constructor should typically only have minimal work to do.  The thing you want to be careful of is to insure that the object is left in a viable state.  One thing you have to be careful of is that the Dispose method cannot be used and any managed resources need to be cleaned up in your finally block.  So if you are likely to cause exceptions, handle them carefully.  See MSDN for more details.

Desctructors
Exceptions that occur during the descructor execution are discarded and the destructor terminated, unless you have a base class destructor.

Exceptions and Using Statements
It is considered a better practice to wrap your using statements with a Try-Catch-Finally block instead of within the Using statement brackets.  FYI.

Other Resources on Exceptions
http://msdn.microsoft.com/en-us/library/ms173163.aspx (MSDN)
http://msdn.microsoft.com/en-us/library/aa664609(v=vs.71).aspx (MSDN)
http://msdn.microsoft.com/en-us/library/aa355056.aspx

0 comments:

 
Toggle Footer
Top