Вы находитесь на странице: 1из 12

CSharp.

NET Tutorial Day 14

In previous article, we have discussed what are Abstract Classes and Abstract
Methods, a brief discussion on what is Interface, in how many ways we can categorize
inheritance i.e. Implementation Inheritance and Interface Inheritance, what
is Structure, what are differences between Class and Structure, what are Access
Specifiers like private, internal, protected, protected internal, public along with
syntaxes and examples, etc

Please find below the link for accessing the article


CSharp.NET Tutorial - Day 13
Now, in this article we will discuss what are Exceptions, what is Exception Handling
mechanism, what are Compile time errors, what are Runtime errors, what is Abnormal
Termination of the Program, what is try, catch, and finally blocks and interrelation in
between try, catch and finally, what are System Exceptions, what are Application
Exceptions, who to throw an exception along with syntaxes and examples, etc

Exceptions and Exception Handling

We may come across two different types of errors when we are working with an
application. Those are
1) Compile time errors
2) Runtime errors

An error that comes into picture at the time of compilation of a program is called as
compile time error. Basically, these types of errors may come arise due to syntactical
mistakes and usually they will not be considered as dangerous.

An error that comes into picture when we execute the program is called as Runtime
error. This can also be called as Exception. This Runtime error will come into
picture because of various reasons like wrong implementation of logic, wrong input
supply to program, missing of required resources, etc.

Here, Runtime errors are dangerous because whenever a runtime error occurs in a
program the program terminates abnormally on the same line where exception
occurred without executing the next consequence lines of code even if the code is no
way related with that exception occurred.

Note: Whenever an exception occurs in a program and the program is getting


terminated abnormally, it will display the reasons for abnormal termination of
program.

Question) Who will be responsible for abnormal termination of Program whenever an


exception occurs in the program?

Answer. Whenever runtime error occurs in a program, our program will be terminated
abnormally by displaying an error message. These two responsibilities will be taken
care by some predefined classes known as Exception Classes relating with each
different type of runtime errors provided with different exception classes defined
under System namespace.

Basically, every exception class is responsible for two things, which are as follows:
1) Abnormal Termination of the Program
2) Displaying of error message that is related with the exception that has occurred.

We can implement Exception classes as below

Exception Handling

As we have discussed above, whenever exceptions occur in a program, the program


gets terminated abnormally without executing the code which is not related to the
exception. If we want to stop the abnormal termination and execute the code which is
not related to the exception, we need to adopt the concept of Exception Handling.

To handle an exception, we need to enclose the code under some special blocks called
try and catch, which should be used like below.

try
{
//statements which causes exceptions
//statements which doesn't require execution when exception occurs
}
catch (<exception> <var>)
{
//statements which requires execution only when exception occurs
}

//we can place multiple catch blocks if required

If the code is enclosed under try and catch blocks then execution of the code takes
place as below.

If all the code under try is executed successfully (i.e. no exception occurred) from
the last statement of try control directly jumps to the statement, which is present
after all catch blocks.

If any statement under try comes across an exception from that line the control
directly jumps to searching for if any particular matching catch block is there. If any
matching catch block is available, abnormal termination stops there and executes the
code under that particular catch block. From there again, it jumps to the statement
after all the catch blocks.

If matching block is not available, abnormal termination occurs again.

Add a class ExceptionEx.cs and write the below code

class ExceptionEx
{
static void Main()
{
int x, y, z;
try
{
Console.WriteLine("Enter x value:");
x = int.Parse(Console.ReadLine());
Console.WriteLine("Enter y value:");
y = int.Parse(Console.ReadLine());

if (y == 1)
return;
z = x / y;
Console.WriteLine(z);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
Console.WriteLine("Finally Block:");
}
Console.WriteLine("End of the program");
Console.ReadLine();
}
}

Note: In the above case if the value to the divisor given as 1, execution of the
program will be stopped because we are using a return statement in the case but
before stopping program to execute. If present, the program will stop execution after

executing the finally block because finally block must execute at any cost if the
execution entries into try.

Message is a property that return an error message which is associated with the
exception occurred in the program.

Message is a virtual property, which is declared under parent class exception so


each child class like FormatException, DivideByZeroException, etc are overloading
the Message property by providing appropriate error message related to that
Exception.

Note: Here, Message is a ReadOnly property.

public class DivideByZero Exception : Exception


{
public override string Message
{
get
{
return "Attempted to divide by Zero";
}
}
public class Format Exception:Exception

{
public override string Message
get
{
return "Input string was not in a correct format"
}
}
}

Note: Based on the same process, we can also define our own exception classes
wherever required. Try, catch and finally blocks can be used in three different
combinations.

1) try and catch: Here, exceptions will be handled.


2) try catch and finally: Here, exceptions will be handled and a set of statements get
executed at any cost.
3) try and finally: Here, exceptions will not be handled but a set of statements will be
executed at any cost.

Basically, Exceptions are two types


1) System Exceptions
2) Application Exceptions

Exception which is raised implicitly on same predefined error conditions is called


System Exception.

Eg:
DivideByZero, Format Exception, NullReference Exception etc

Exceptions which are raised explicitly by the programmer on their own conditions
called Application Exception or User-Defined Exception.

We can raise an Exception in a program as below

Step1: Create the object of any Exception class

Eg:
FormatException ex = new FormatException ( );

Step2: Throw the object we created using throw statement

Eg:
throw ex

question) Which class object should be used for raising an Exception explicitly?

Answer. If we want to raise exception explicitly, we have two different options.


1) Create the object of predefined class Application Exception by passing the required
error message and throw that object.
2) Create our own Exception class following the process we have previously discussed
and create objects of those classes to throw.

Add a Codefile ThrowEx.cs and write the below code.

using System;
namespace OOPSProject
{
class OddNumberException: Exception
{
public override string Message
{
get
{
return "Divisor Cannot be an Odd number";

}
}
class ThrowEx
{
static void Main()
{
int x,y,z;
Console.WriteLine("Enter x value:");
x=int.Parse(Console.ReadLine());
Console.WriteLine("Enter y value:");
y=int.Parse(Console.ReadLine());
if(y%2>0)
{
throw new OddNumberException();
}
z=x/y;
Console.WriteLine(z);
Console.WriteLine("End of the Program");
Console.ReadLine();
}

}
}
}

Happy Learning.!!!!!

Вам также может понравиться