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