CSharp - Exception Throwing Exceptions

Introduction

You can throw Exceptions in your code.

The following code shows how to throw a System.ArgumentNullException in case of null parameter value.

Demo

using System;

class Test//  w  w w . j a v a2s. co m
{
    static void Display(string name)
    {
        if (name == null)
            throw new ArgumentNullException(nameof(name));

        Console.WriteLine(name);
    }
    static void Main()
    {
        try
        {
            Display(null);
        }
        catch (ArgumentNullException ex)
        {
            Console.WriteLine("Caught the exception");
        }
    }
}

Result

throw expressions

You can throw exceptions in in expression-bodied functions:

public string Test() => throw new NotImplementedException();

A throw expression can appear in a ternary conditional expression:

string ProperCase (string value) =>
       value == null ? throw new ArgumentException ("value") :
       value == "" ? "" :
       char.ToUpper (value[0]) + value.Substring (1);

Rethrowing an exception

You can capture and rethrow an exception as follows:

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

We can rethrow the same exception.

throw ex;

The StackTrace property of the newly propagated exception would no longer reflect the original error.

You can rethrow a more specific exception type. For example:

try
{
    ... // Parse a DateTime from XML element data
}catch (FormatException ex){
    throw new XmlException ("Invalid DateTime", ex);
}

XmlException is created from original  exception,  ex,  as  the  second  argument.  

Related Topics