Introduction

All exceptions in .NET are objects.

System.Exception is the base class for the exceptions.

We use four keywords to deal with C# exceptions: try, catch, throw, finally

We guard an exception with try/catch block. The code that may throw an exception is placed inside a try block.

The exceptional situation is handled inside a catch block.

We can use multiple catch blocks with a try block.

A particular catch block handles the sudden surprises.

The code in the finally block will run regardless. It is placed after a try block or a try/catch block.

The following code shows how to handle the divide-by-zero exception.

Demo

using System;

class Program/*from  w w  w . j a  va 2s  .  c  o  m*/
{
    static void Main(string[] args)
    {
        int a = 100, b = 0;
        try
        {
            int c = a / b;
            Console.WriteLine(" So, the result of a/b is :{0}", c);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Encountered an exception :{0}",
                ex.Message);
        }
        finally
        {
            Console.WriteLine("I am in finally.You cannot skip me!");
        }
    }
}

Result

Related Topic