CSharp - method throws an exception.

Introduction

A method can throw an exception with the throw keyword.

In the following example, we have thrown a DivideByZeroException from the Divide method when the divisor is 0, and then we handled it inside a catch block.

Demo

using System;

class Program/*ww w.  j  av  a 2 s .c o  m*/
{
    static int a = 100, b = 0, c;
    static void Divide(int a, int b)
    {
        if (b != 0)
        {
            int c = a / b;
        }
        else
        {
            throw new DivideByZeroException("b comes as Zero");
        }
    }
    static void Main(string[] args)
    {
        try
        {
            Divide(a, b);
            Console.WriteLine("Division operation completed");
        }
        catch (DivideByZeroException ex)
        {
            Console.WriteLine("Encountered an exception :{0}", ex.Message);
        }
    }
}

Result

Related Topic