CSharp/C# Tutorial - C# Exception

The using statement

Many classes encapsulate unmanaged resources.

These classes implement System.IDisposable, which defines a single parameterless method named Dispose to clean up these resources.

The using statement provides an elegant syntax for calling Dispose on an IDisposable object within a finally block.

The following:

using (StreamReader reader = File.OpenText ("file.txt")) {

is equivalent to:

StreamReader reader = File.OpenText ("file.txt");
try {
} finally {
   if (reader != null) ((IDisposable)reader).Dispose();

Throwing Exceptions

Exceptions can be thrown either by the runtime or in user code.

In this example, Display throws a System.ArgumentNullException:

class Main {
   static void Display (string name) {
      if (name == null){
          throw new ArgumentNullException ("name");
      Console.WriteLine (name);
   static void Main() {
       try { 
          Display (null); 
       } catch (ArgumentNullException ex) {
          Console.WriteLine ("Caught the exception");

Rethrowing an exception

You can capture and rethrow an exception as follows:

try { 
} catch (Exception ex){
    // Log error
    throw; // Rethrow same exception

Key Properties of System.Exception

The most important properties of System.Exception are the following:

  • StackTrace
    A string representing all the methods that are called from the origin of the exception to the catch block.
  • Message
    A string description of the error.
  • InnerException
    The inner exception that caused the outer exception.

Common Exception Types

The following exception types are used widely throughout the CLR and .NET Framework.

  • System.ArgumentException
    Thrown for an illegal argument.
  • System.ArgumentNullException
    Subclass of ArgumentException that's thrown when a function argument is null.
  • System.ArgumentOutOfRangeException
    Subclass of ArgumentOutOfRangeException that's thrown when a numeric argument is too big or too small.
  • System.InvalidOperationException
    Thrown when the state of an object is unsuitable for a method.
  • System.NotSupportedException
    Thrown for a supported functionality.
  • System.NotImplementedException
    Thrown for a not implemented function.
  • System.ObjectDisposedException
    Thrown when the object upon which the function is called has been disposed.

The TryXXX Method Pattern

int type defines two versions of its Parse method:

public int Parse (string input);
public bool TryParse (string input, out int returnValue);

If parsing fails, Parse throws an exception; TryParse returns false.

You can implement this pattern by having the XXX method call the TryXXX method as follows:

public return-type XXX (input-type input) {

return-type returnValue;

if (!TryXXX (input, out returnValue))
    throw new YYYException (...)
    return returnValue;