You are here

Exception in C#

Preventing the finally block from running can be achieved by using Environment.FailFast. This method has two different overloads, one that only takes a string and another one that also takes an exception. When this method is called, the message (and optionally the exception) are written to the Windows application event log, and the application is terminated. The event log can be seen from the windows log system. Environment class has a method

public static void FailFast ( string message ); 
public static void FailFast ( string message, Exception exception );

Finally block may not call also if we have an infinite loop in our try block.

        string s = "40";
        try
            {
                int i = int.Parse(s);
                if (i == 40) Environment.FailFast("Special number entered");
            }
            finally
            {
                Console.WriteLine("Finally block never called");
            }

It’s important to make sure that your finally block does not cause any exceptions. Let's we try to throw exception by our selves. Following simple code shows how we do that. We test a number if it is higher than 500 then we through an exception of type ArgumentOutOfRangeException. There are different type of exception which can be consulted with the pages (https://msdn.microsoft.com/en-us/library/system.argumentoutofrangeexception(v=vs.110).aspx)


public class myApp
{
    public static int TestNumber ( int number )
    {
        if (number > 500)
            throw new ArgumentOutOfRangeException ( number.ToString ( ), "Number should be less than 500" );
        return number;
    }

    public static void Main ( )
    {
        int num = 700;
        try
        {
            TestNumber ( num );
        }
        catch (ArgumentOutOfRangeException ex)
        {
            Console.WriteLine ( ex.Message );
        }
        finally 
        {
            Console.WriteLine ( "The Final block" );
        }
    }
}

Output of the program

We should not try to reuse exception objects. Each time we throw an exception, we should create a new one, especially when working in a multi threaded environment, the stack trace of our exception can be changed by another thread.

When we catch exception we can do with the exception any of the followings:
A. Use the throw keyword without an identifier.
This option rethrows the exception without modifying the call stack.
B. Use the throw keyword with the original exception.
Call stack is reset to the current location, we don't know where is the origin of the exception.
C. Use the throw keyword with a new exception.
Same as completely new exception

Later version of C# added rethrowing an exception. We can use the ExceptionDispatchInfo.Throw method, which can be found in the System.Runtime.ExceptionServices namespace. This method can be used to throw an exception and preserve the original stack trace. Following example shows how to use it. Original message has been preserved.


public class myApp
{
    public static int TestNumber ( int number )
    {
        if (number > 500)
            throw new ArgumentOutOfRangeException ( number.ToString ( ), "Number should be less than 500" );
        return number;
    }

    public static void DoTest (  )
    {
        int num = 700;
        ExceptionDispatchInfo possibleException = null;
        try
        {
            TestNumber ( num );
        }
        catch (ArgumentOutOfRangeException ex)
        {
            Console.WriteLine ( "DoTest :" + ex.Message );
            possibleException = ExceptionDispatchInfo.Capture ( ex );
        }
        //It can be trown outside of the block
        if (possibleException != null)
        {
            possibleException.Throw ( );
        }
    }

    public static void Main ( )
    {       
        try
        {
            DoTest ( );
        }
        catch (Exception ex)
        {
            Console.WriteLine ( "Main :" + ex.Message );
        }
        finally 
        {
            Console.WriteLine ( "The Final block" );
        }
    }
}

Creating own exception

By convention, we should use the Exception suffix in naming all our custom exceptions. It’s also important to add the Serializable attribute, which makes sure that our exception can be serialized and works correctly across application domains (for example, when a web service returns an exception).When creating our custom exception, we can decide which extra data you want to store. We should never inherit from System.ApplicationException. The original idea was that all C# runtime exceptions should inherit from System.Exception and all custom exceptions from System.ApplicationException. However, because the .NET Framework doesn’t follow this pattern, the class became useless and lost its meaning.
See the code below.

[Serializable]
public class OwnNumberException : Exception, ISerializable
{
    public int MyNumber { get; set; }
   public OwnNumberException(int number, string amessage): base(amessage)
    {
        MyNumber = number;        
    }
}

public class myApp
{
    public static int TestNumber ( int number )
    {
        if (number > 500)
            throw new OwnNumberException ( number, "Wrong number" );
        return number;
    }

    public static void DoTest (  )
    {
        int num = 700;
        ExceptionDispatchInfo possibleException = null;
        try
        {
            TestNumber ( num );
        }
        catch (OwnNumberException ex)
        {
            Console.WriteLine ( "DoTest :" + ex.Message );
            possibleException = ExceptionDispatchInfo.Capture ( ex );
        }
        //It can be trown outside of the block
        if (possibleException != null)
        {
            possibleException.Throw ( );
        }
    }

    public static void Main ( )
    {       
        try
        {
            DoTest ( );
        }
        catch (Exception ex)
        {
            Console.WriteLine ( "Main :" + ex.Message );
        }
        finally 
        {
            Console.WriteLine ( "The Final block" );
        }
    }
}