Exception Handling

Exceptions are unforeseen errors that happen in your programs. Most of the time, you can, and should, detect and handle program errors in your code.
  • 1988

Introduction

Exceptions are unforeseen errors that happen in your programs. Most of the time, you can, and should, detect and handle program errors in your code. For example, validating user input, checking for null objects, and verifying the values returned from methods are what you expect, are all examples of good standard error handling that you should be doing all the time. In structured exception handling, blocks of code are encapsulated, with each block having one or more associated handlers. Each handler specifies some form of filter condition on the type of exception it handles. When an exception is raised by code in a protected block, the set of corresponding handlers is searched in order, and the first one with a matching filter condition is executed. A single method can have multiple structured exception handling blocks, and the blocks can also be nested within each other .If an exception occurs in a method that is not equipped to handle it, the exception is propagated back to the calling method , or the previous method. If the previous method also has no exception handler, the exception is propagated back to that method 's caller, and so on. The search for a handler continues up the call stack, which is the series of procedures called within the application. If it fails to find a handler for the exception, an error message is displayed and the application is terminated.

Example : This is a simple example of a exception handling.

Code

using System; 

class Program

{

    static void Main()

    {

        try

        {

            int value = 1 / int.Parse("0");

        }

        catch (Exception ex)

        {

            Console.WriteLine("HelpLink = {0}", ex.HelpLink);

            Console.WriteLine("Message = {0}", ex.Message);

            Console.WriteLine("Source = {0}", ex.Source);

            Console.WriteLine("StackTrace = {0}", ex.StackTrace);

            Console.WriteLine("TargetSite = {0}", ex.TargetSite);

        }

    }

} 

© 2019 DotNetHeaven. All rights reserved.