Exception Handling in C#

In simplest of the words, exception is basically an error in the program which either hampers the compilation of the code or crashes the code at runtime.

There are two types of exceptions in C#: Compile time errors and Run time exceptions.

Compile Time Errors

Compile time errors are those exceptions that do not let the code to compile. A typical example of a compile time exception is missing a semi-colon at the end of the line, missing a bracket and other similar syntax errors. Compile time errors are not dangerous as they are caught before actual execution of the program and can be corrected ahead of the execution.

Runtime Exceptions

Runtime exceptions are not caught at compile time. A program can be compiled even it has runtime errors. A typical example of a runtime exception is accessing array index which is out of bound or dividing a number by zero. Runtime exceptions are dangerous as they do not always occur and are never caught at runtime. Therefore, some special mechanism is required that can be used to handle these runtime exceptions.

In C#, try and catch statements are used to handle runtime exceptions. The code block which is vulnerable to runtime exceptions is enclosed inside the try block and the code that is to be executed if an exception occurs is enclosed in the catch block. Consider following example to see try and catch in action.

´╗┐using System;
namespace CSharpTutorials {

    class Tutorial {
        static void Main(string[] args) {

            int numerator = 10;
            int denom = 0;
            int result;

            try {
                result = numerator / denom;
            }
            catch {
                Console.WriteLine("Division by zero not possible.");
            }
            Console.ReadKey();
        }
    }
}

Download the code

In the above code the denominator is zero, so when the program executes a runtime exception will occur. Since this code is within try block, the control will shift to catch block and the statements inside the catch block shall execute and program will not crash as is the case with un-handled exceptions.

<<< C# Abstract class and abstract methodExtension Methods in C# >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .