Below is the code which calculates the factorial of a number. If we pass a negative number as an argument it will throw a user defined exception. For this we have created a class which inherits an "exception" superclass and it contains an overriden tostring() method to print the user defined exception message.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exception_inheritance_demo
{
class MyEx : Exception
{
public override string ToString()
{
return "No not allowed";
}
}
class A
{
void facto(int n)
{
if (n < 0)
throw new MyEx();
else
{
int f = 1;
while (n > 0)
{
f = f * n;
n--;
}
Console.WriteLine("Factorial="+ f.ToString());
}
}
static void Main(string[] args)
{
A a1 = new A();
try
{
a1.facto(4);
a1.facto(-4);
a1.facto(3);
}catch(Exception ex)
{
Console.WriteLine("{0}", ex.ToString());
}
Console.ReadLine();
}
}
}
Comments
Post a Comment