applicationexception c# |
APPLICATION EXCEPTION
“The Type
of exception that define by programmer at the programming time for their own
project, these exception is not predefined the system libraries these are built
by programmer based on their own need.”
Steps to Define an Application Exception (Syntax)
There are
few step involve in Application exception definition.
1. Define a Class with a specific exception name and specify its
return type.
[<Modifier>] Class <Ex.Name>
{
//;
}
2. Build inheritance with the Pre-defined Exception class, the
parent may be system exception or any other class but the most prefer parent
class will be Application Exception.
[<Modifier>]
Class <Ex.Name>: Application Exception
{
//;
}
3. Here the base class will be the Exception class because the
Application Exception is further inherited by Exception class. There is a
predefined virtual Massage method in Exception class override it by your own
need method’s Massage. Also specify the return type usually it is string.
[<Modifier>]
Class <Ex.Name>: Application Exception
{
[<Modifier>]
<Return> override Message ()
{
Statement; //Here the
massage will write that should display if the exception
Rise by help of get accessor, see example below
}
}
4. Now it’s time to call the exception, in case of system exception
the CLR make instance and throw the exception for abnormal terminate, but here
the programmer responsible to create the instance of exception and have to
throw it explicitly. Like
By specifying the condition
If (condition)
{
<Exception-Name> obj
= new <Exception-Name> ( );
Throw obj;
}
But we can throw without creating instance
name because we are not going to call any member of class so no need of
instance name ‘obj’ simply you can do
If (condition)
{
Throw new <Exception-Name>
( );
}
Throw
Throw is a
keyword which is used to throw the exception, see example for better understand.
EXAMPLE OF APPLICATION EXCEPTION IN C#
Consider a
problem that raised an application exception if user input an odd integer divisor.
Exception class
namespace AppException
{
class DivideByOddNoException : ApplicationException
{
public override string Message
{
get
{
return "Attempted to
Divide by odd number";
}
}
}
}
|
Main class
namespace AppException
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter an
integer dividend value");
int dividend = int.Parse(Console.ReadLine());
Console.WriteLine("Enter an
integer divisor");
int divisor = int.Parse(Console.ReadLine());
if (divisor % 2 == 1)
{
throw new
DivideByOddNoException();
}
int b = s / a;
Console.WriteLine("The Result
is "
+ b);
Console.ReadKey();
}
}
}
}
|
0 comments:
Post a Comment
Please do not enter any spam link in the comment box