Whenever a run- time error occurs under the program abnormal termination is occuring so we will be facing so many problems in the application. To overcome the problems we are provided with a mechanism known as Exception Handling.
Exception Handling is a process of stopping the abnormal termination of the program whenever the exceptions are terminating the program in case of run time error. If we can stop the abnormal termination of a program we will be getting following advantages :
Exception Handling is a process of stopping the abnormal termination of the program whenever the exceptions are terminating the program in case of run time error. If we can stop the abnormal termination of a program we will be getting following advantages :
- We can make the statement which are not associated with the error.
- We can display a user friendly error message to the end user so that he can resolve the error, got occurred provided if it is in his hands.
- We can also perform some corrective actions to come out of a problems that may occur due to error.
To handle an exception we need to enclose our code under some special blocks known as try catch block which should be used as following:
try
{
-statements which requires execution when the run time error occurs.
-statements which does not require execution only when the run time error occurs.
}
catch
{
-statements which requires execution only when the run time error occurs.
}
[--< multiple catch blocks if required >--]
Add a class Exception demo.cs and write the following code:
using System; namespace CSharpConsole { class ExceptionDemo { 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()); z = x / y; Console.WriteLine(z); } catch (DivideByZeroException ex1) //ex1 is a variable of class DivideByZeroException { Console.WriteLine("Divisor must not be zero"); } catch (FormatException ex2) //ex2 is a variable of class FormatException { Console.WriteLine("Input must be numeric"); } catch (Exception ex3) { Console.WriteLine(ex3.Message);//message is a read only property } { Console.WriteLine("End of the program"); Console.ReadLine(); } } } }
No comments:
Post a Comment