Introduction

The exceptions are anomalies that occur during the execution of a program. Exception handling is a mechanism in .NET framework to detect and handle run time errors. They can be because of user, logic or system errors. If a user (programmer) does not provide a mechanism to handle these anomalies, the .NET runtime environment provides a default mechanism, which terminates the program execution.

In C# there are three keywords Try, Catch, and Finally for handling exceptions.

e.g.

try
{
     // this can cause an exception.
}
catch (Type x)
{
    // for handling the exception.
}
finally
{
    //this will execute.
}

Exception Class

Following are some common exception classes.

Custom Exception in C#

According to the .NET framework documentation, SystemException is meant only for those exceptions defined by the common language runtime whereas ApplicationException is intended to be used by user code. An "ApplicationException is thrown by a user program, not by the common language runtime. If you are designing an application that needs to create its own exceptions, derive from the ApplicationException class. ApplicationException extends Exception, but does not add new functionality. This exception is provided as means to differentiate between exceptions defined by applications versus exceptions defined by the system."

Steps to Create Custom Exception

  1. Implement error handling in the user interface.
  2. Create and implement custom error messages.
  3. Create and implement custom error handlers.
  4. Raise and handle errors.

Illustrates a Custom Exception

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
 namespace ConsoleApplication2
{
    class MyException :ApplicationException
    {
        public void MyExceptiona()
        {
            MessageBox.Show("An exception occured");
        }
        public void MyDivideException()
        {
            MessageBox.Show("Exception occured, divisor should not be zero");
        }
    }
 
    class TestMyException
    {
        public static void Main(String[] arg)
        {
            int d, div, res;
            div = Int32.Parse(Console.ReadLine());
            d = Int32.Parse(Console.ReadLine());
            try
            {
                if (div == 0)
                {
                    throw new MyException();
                }
            }
            catch (MyException e)
            {
                e.MyDivideException();
            }
 
            res = d / div;
            Console.WriteLine("Result:{0}", res);
        }
    }
}

Output

Custom Exception in C#

When we enter the first value as 0 and second value as 9, it will show an Error message Box as shown in the following figure:

Custom Exception in C#

Here we have created our own custom exception MyDivideException() which when generated, shows an Error message box as "Exception occured, divisor should not be zero"

Catching and handling the custom exception

try
{
    if (div == 0)
    {
        throw new MyException();
    }
}
catch (MyException e)
{
     e.MyDivideException();
}
     res = d / div;
     Console.WriteLine("Result:{0}", res);
}

Here in the try block statements it might throw an exception whereas catch block handles that caused by the try block if one exists.

Resources

Here are some useful related resources: