Mar 12, 2007

Table of Contents

Notes on C# exception handling.

Usage

try { // code to test }
catch (  ExceptionA ) { ... }
catch ( ExceptionB ) { ... }
catch { // catch ALL other exception here that weren't caught above!!! }
finally { } // executes whether exception occured or not.
... // executes only if there is no exception

Example:

try {inputFile = new System.IO.StreamReader("data\\test.txt");}
catch (System.IO.IOException) {...}

finally block must have a try block, but not necessarily catch block

// EX:
try { ....}
finally {...}// this is ok. however, exception should still be caught somewhere

Exception vs Exception Var

catch (IOException e) vs (IOException)
first case generates warning/error msg???? not sure. the first ex works fine

Example code:

try {
    //some code
}
catch( DirectoryNotFoundException ex) {
    Console.WriteLine(ex.Message); // if Message was set by throw
}

throw

throw new System.Exception();     // throw the most general exception type. 

throw new Exception("optional message") ;
message string can be viewed in ex.Message property

if (!Directory.Exists(_finishedDir)) {
				throw new DirectoryNotFoundException(_finishedDir);
			}

Extra information

    e.Data["ExtraInfo"] = "Information from NestedRoutine1.";
    e.Data.Add("MoreExtraInfo", "More information from NestedRoutine1.");
        throw e;

Example:

//Beginning C# Video O'Reilly
static decimal Max(decimal[] values) {
    // It's always good to check for null as the FIRST thing!!!
    if (values==null) throw new ArgumentNullException("values", "Array cannot be null");
    else if (values.Length == 0) throw new ArgumentException("values", "cannot be null");
    ...
}

Exception types

All Exceptions are derived from System.Exception type

Some common exceptions to throw:

throw new NotImplementedException();

e.Message: descriptive string message property
e.StackTrace    # displays call stack
e.HelpLink  : help link. custom exception can set this property.

Custom Exceptions

public class MyException : System.Exception
{
    public MyException (string message) :
        base (message)  // pass message to base class
    { }  // no need to do anything special
}

...
throw new MyException("hi");