C# Try/Catch

April 2, 2009

C# Intro to Try/Catch

Using “Try/Catch” in C#

A Try/Catch block is the error handling mechanism for .NET.

What you will learn here:
1) How to wrap your code in a “Try” statement
2) How to catch and display errors in the “Catch” statement
3) The three major properties of the Exception class (Message, Source, StackTrace) and the ToString() method.

Code for you to copy:


        private void btnAddTwoNumbers_Click(object sender, EventArgs e)
        {
            try
            {
                decimal decimalResult = AddTwoNumbers(txtNumber1.Text,
                                                      txtNumber2.Text);
                txtResult.Text = Convert.ToString(decimalResult);
            }
            catch (Exception ex)
            {
                MessageBox.Show(
                    "You did not enter two valid numbers, please try again.\r\n"
                    + " Message=" +  ex.Message + "\r\n"
                    + " Source=" +  ex.Source+ "\r\n"
                    + " StackTrace=" +  ex.StackTrace + "\r\n"
                ); 

            }

        }

        // This routine was created to demonstrate the StackTrace
        private static decimal AddTwoNumbers(string A, string B)
        {
            decimal decimalA = decimal.Parse(A);
            decimal decimalB = decimal.Parse(B);
            decimal decimalResult = decimalA + decimalB; 

            return decimalResult;
        }
    }

Video Demonstration:

Part 1 of 2



Part 2 of 2

Filed under C# Try/Catch by Administrator

Permalink Print Comment