An exception is a problem that arises during program execution. Exceptions are expected to happen within the code of an application for many reasons (known or unknown). Below is a tutorial on how exceptions work in C#.

Exception Handling in C#

Exception handling is a feature in C# to handle (exceptional circumstances) runtime errors in order to maintain normal execution of an application even after an exception occurs. It transfers control from one part of the program to another.

Exception classes

All exceptions classes are derived from the base class: System.Exception class.

Keywords

C# exception handling uses 4 keywords.

  • Try: The ‘try’ block is used to encapsulate the code that might throw an exception. In case it throws an exception, it is handled by the corresponding catch block.
    The try block must e followed by a catch block or a ‘finally’ block or both.
  • Catch: Whenever an exception occurs, the catch block is executed.
  • Finally: The ‘finally’ block is used to execute any important part of the program that needs to be executed whether or not an exception is thrown. The ‘finally’ block is preceded by a try/catch block
  • Throw: The ‘throw’ block is used to create a new exception that ultimately leads to try/catch block.

Syntax

The try/catch block is placed around the code that might throw an exception. The general syntax is given as:

            try
            {
                // exceptional statements
            }
            catch (Exception e1)
            {
                // exception handling code
            }
            try
            {
                // exceptional statements
            }
            catch (Exception e2)
            {
                // exception handling code
            }
            finally
            {
                // final statements to be executed
            }

Example Using Try/Catch block

        class program
        {
            static void Main()
            {
                try
                {
                     SendEmail();
                }

                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                }
            }
        }

Multiple Catch block

        static void Main()
        {
            Console.Write("Please enter the numbers to operate upon");
            try
            {
                int num1 = int.Parse(Console.ReadLine());
                int num2 = int.Parse(Console.ReadLine());
                int result = num1 / num2;
                Console.WriteLine(result);
            }
            catch (DivideByZeroException e1)
            {
                MessageBox.Show(e1.Message);
            }
            catch (InvalidCastException e2)
            {
                MessageBox.Show(e2.Message);
            }
        }

Finally block

            static void Main()
            {
                int DevideBy = 0;
                int result;
                try
                {
                    result = 5 / DevideBy;
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                }
                finally
                {
                    MessageBox.Show("Inside finally block");
                }
            }

Nested Try-Catch

        static void Main()
        {
            Employee emp = null;
            try
            {
                try
                {
                    emp.EmployeeName = string.Empty;
                }
                catch (Exception e)
                {
                    MessageBox.Show("Inner catch block");
                }
            }
            catch (Exception e1)
            {
                MessageBox.Show("Outer catch block");
            }
        }

Throw Block

    static void Main()
    {
        Lecturer lect = null;
        try
        {
            PrintLecturerName(lect);
        }
        catch (Exception e)
        {
            MessageBox.Show(e.Message);
        }
    }

    public static void PrintLecturerName(Lecturer lect)
    {
        if (lect == null)
        {
            throw new NullReferenceException("Object is empty");
            MessageBox.Show(lect.LEcturerName);
        }
    }

Important

• The try block must be followed by a catch block or a finally block or even both
• Multiple catch block is allowed
• The finally block will always execute whether an exception occurs or not
• The finally block is not allowed to leave the control until complete execution of the program
• Nested try-catch blocks are allowed.

Related Articles

How to Use Throw Expressions in C# 7.0

Objects and Classes in C#

Replace hostname in URL using C#

 

Last modified: February 12, 2019

Comments

Write a Reply or Comment

Your email address will not be published.