5.4 Exception Handling

File Location

  1. Right click on your solution

  2. Go to Add > New Project and select Console App (.NET Framework)

  3. Name it ExceptionHandling

Discussion

Try catch statements can be used to handle issues you expect to happen within your program. What the catch part of the statement will do is it will catch an error you expect could happen and make it do something else so that your program will not crash. Within C#, an exception is a response to a problem that happens while the program is running. An example could be an attempt to divide by zero. C# exceptions provide a way to transfer control from one part of a the program to another. We will use four keywords to go about this handling.

  1. Try − A try block identifies a block of code for which particular exceptions are activated. It is followed by one or more catch blocks.

  2. Catch − A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception.

  3. Finally − The finally block is used to execute a given set of statements, whether an exception is thrown or not thrown. For example, if you open a file, it must be closed whether an exception is raised or not.

  4. Throw − A program throws an exception when a problem shows up. This is done using a throw keyword.

Syntax

If a block will raise an exception, then a method can catch an exception using a series of try/catch keywords. Try/catch blocks can be placed around code that might generate an exception. Code that is wrapped around by a try/catch statement is referred to as protected code. Try/catch blocks look something like this:

//      1
    class DivNumbers {
//      2
      int result;
//      3
      DivNumbers() {
         result = 0;
      }
//      4
      public void division(int num1, int num2) {
//      5
         try {
//          6
            result = num1 / num2;
//          7
         } catch (DivideByZeroException e) {
            Console.WriteLine("Exception caught: {0}", e);
//          8
         } finally {
            Console.WriteLine("Result: {0}", result);
         }
      }

      static void Main(string[] args) {
         DivNumbers d = new DivNumbers();
         d.division(25, 0);
         Console.ReadKey();
      }
   }
  1. Declaring our class

  2. Declaring our fields

  3. Constructor building out our class

  4. Division method that will hold our exception handling

  5. Declaring our try statement

  6. Our code tries to divide our two parameters

  7. The catch method will stop our code and throw an exception if it tries to divide by 0 (using DivideByZeroException)

  8. Our finally statement will run if it passes through our catch statements and does not get caught

Discussion

  1. We have a method within our DivNumbers class which returns a 0.

  2. Next we have a method called division which has two integers as parameters with try, catch, and a finally statement within the method

    • The try statement is saying "look to see if the method attempts to divide the two integers"

    • The catch statement is then activated if the try statement does find what it is looking for and will print out "Exception caught: (file path)"

    • The finally statement will be executed no matter what and will print the result.

Another Example

In this example we will simulate when a user will be entering in their age. We will have exceptions that catch if the user puts in a number larger than 115 or less than 0. Since humans can't be negative years old and probably won't live to be older than 115 years.

    class Program
    {
        static void Main(string[] args)
        {
            Age ageObjectVariableName = new Age();
            try
            {
                ageObjectVariableName.showAge();
            }
            catch (AgeException exception)
            {
                Console.WriteLine("TempIsZeroException: {0}", exception.Message);
            }
            Console.ReadLine();
        }
    }

    public class Age
    {
        int age = -5;
        public void showAge()
        {
            if (age >= 115)
            {
                throw (new AgeException("Humans don't usually live that long.  Make sure you are entering the right age."));
            }
            if (age < 0)
            {
                throw (new AgeException("Negative numbers cannot be entered here")); 
            }
            else
            {
                Console.WriteLine("{0} years old", age);
            }
        }
    }

    public class AgeException : Exception
    {
        public AgeException(string message) : base(message)
        {

        }
    }
  1. First lets stub out our Age class which will have the age we are checking and a method called showAge() with if else statements checking that age for large and negative numbers.

  2. Next we will stub out our AgeException class which our try catch statement will later refer to.

    • We will also inherit an new instance of the class which will throw our specific messages when an error is thrown instead of C#'s default message.

  3. Lastly within our Program's Main() method, we will instantiate a new object of Age followed by a try and catch statement.

    • The try statement checks to see if the showAge() method ran.

    • The catch statements takes in the AgeException class and then print out the appropriate message based on which if statement it hits.

    Next: Structs

Last updated