C Sharp/Exceptions
< C SharpException Handling is a main feature of OOP Concepts. Before going to know about this Exception Handling we should know what is an Exception?. Exception is a run time error which occurs while executing the program. Due to this our system may hang or happen some thing. Example:- if we are writing a program to divide two numbers. suppose we have given the fist digit as 4 and the other integer as 0. Like this situation the compiler don't knows what to do. At this situation the system may hang. To over come like this Situations(exceptions(Run time errors))exception handling methods were implemented. The above example exception is called as Arithmetic Exception. Like this we have so many exception handling methods.
For the purpose of Exception handling we will use 4 key words. They are try, catch, throw, finally. In this 4 key words try key word is used to monitor the exceptions which are there in our code. This try key word contains the body. This block will be called as try block. We use to write our code in try block which may generates the exceptions. The try block will be as follows.
try { Statement 1; Statement 2; - - - - - - - - - - - - - - - - - - }
The statements which are in the try block is called as body of the try block. When it monitor the exceptions then those exception will be thrown. Then the exceptions will be caught by catch block. Followed by the try block catch block should be there. This block can be the optional. A try block can have zero or more number of catch blocks. The catch block syntax will be as follows.
catch (parameters) { Exception statement 1; Exception statement 2; - - - - - - - -- - - -------------------- }
From the above syntax catch block contains the arguments in that the data type will be treated as the class and the object will be treated as the variable like a common method.
Example :
int Division(int a, int b) { try { return (a / b); } catch (System.DivideByZeroException dbz) { System.Console.WriteLine("Division by zero attempted!"); return 0; } }