C# Throw Statement

In this chapter you will learn:
  • What is throw statement in C#?
  • What is the functionality of throw statement?
  • How to use throw statement C sharp programming?

Throw statement is used for throwing exception in a program. The throwing exception is handled by catch block. You will learn complete about throw statement in Exception handling tutorial.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace throw_statement
{
    class Program
    {
        static void Main(string[] args)
        {
            int num1, num2, result;

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

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

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

 

When you will execute this code, and input 0 for second input then you will get the Can’t Divide by Zero Exception that is raised by throw statements.

Output

Enter First Number
9
Enter Second Number
0

Error : System.Exception: Cant Divide by Zero Exceptionat Throw_statement.Program.Main<String[] args> in C:\Documents and Settings\Steven\My Documents\Visual Studio 2008\Projects\complete c# code\Chapter4\Throw statement\Throw statement\Program.cs:line 26 __

Summary

In this chapter you learned what throw statement is in C# and how to use it in programming. In next chapter you will learn Checked Statement in C#.

More Articles

 

Share your thought



PLEASE DISABLE ADBLOCKER AND SUPPORT US!

Please support us by enabling ads on this page. Refresh

YOU DON'T LIKE ADS, WE ALSO DON'T LIKE ADS!
 
But we have to show ads on our site to keep it free and updated. We have to pay huge server costs, domain costs, CDN Costs, Developer Costs, Electricity and Internet Bill. Your little contribution will encourage us to regularly update this site.