C# Throw Statement

In this article i am explaining about Throw Exception. Throw statement is used for throwing exception in a program. The throwing exception is handled by catch block.

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Throw_Statement_Example
{
 class Program
 {
 static void Main(string[] args)
 {
 int n1, n2, result;

 Console.WriteLine("Enter First Number");
 n1 = Convert.ToInt32(Console.ReadLine());

 Console.WriteLine("Enter Second Number");
 n2 = Convert.ToInt32(Console.ReadLine());

try
 {
 if (n2 == 0)
 {
 throw new Exception("Can’t Divide by Zero Exception\n\n");
 }
 result = n1 / n2;
 Console.WriteLine("{0} / {1} = {2}", n1, n2, result);
 }
 catch (Exception e)
 {
 Console.WriteLine("Error : " + e.ToString());
 }
 Console.ReadLine();
 }
 }
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *