User:Pasaban/Exceptions and Exception Handling

Lesson Goals
This lesson will focus on functions in the flow of programming in C# via the console. At the end of this lesson you should be able to:
 * Understand various types of exceptions.
 * Comprehend the best practices in programming.
 * Understand the ways to handle exceptions elegantly.
 * Have an overview of Microsoft Application Block.

What is an Exception?
In programing perlance any deviation from expectation can be called as exception (May be this is the dictionary definition as well!). Deviation from expectation may have many form. Like, wrong user input, or, impossible calculations. Most of the time, you can, and you should, detect this early. And you would take measures to take care of that elegantly. These measures are where your exception handling techniques come into play.

However, in some cases you would not be able to predict an exception like in case of run out of system memory, file I/O error, network connectivity error, etc. Though these things are unlikely still you would have to handle them as well. In C# exceptions happens or "thrown" as an object of System.Exception class. And you have to "catch" that to handle, so that code does not crash. For this C# has try-catch block.

Try-Catch Block
The basic structure of the this block is as follws, - try { 		 } Catch (  ) { 		  	} finally { 		 }   is the piece of code that you thing is having a likelyhood of raising exception. This is the main part of the code which your program need to serve its purpose. You have wrapped it in a try-catch-finally block to trap and handle exception. In the catch section you first create an   of the specific   that you foresee and inside, you have the  . You can have as many catch block as you foresee the various exception that the given try block may raise.

'''Remember:Only one catch block runs in a try-catch block. So order the catch blocks such that the most specific catch block runs.'''

The finally block runs at the last irrespective of if the exception occured or not. This block you can use to dispose off the objects or close the database connection if any. this is usefull in the event of exception, as then program will jump out of the try block and perform the catch block straight away.

There can be nested try-catch blocks nested either in try or catch block.

Try-Catch-Finally Block Code Flow
Program will first get into the try block and start executing the steps there. Say, there are 5 steps in the try block. If all the 5 steps ran successfully then it will go to the finally block and execute the steps there. In case, there is an exception at, say, step 3 then program flow will jump into the catch section without executing steps 4 and 5. Now if you have multiple catch then program will check the exception type with each of the catch block. Where it matches with the type or its supertype, that catch block will execute. After that it will perform the finally block.

Remember: A try must have a finally or a catch block but none of the finally or catch block is mandatory.

Approaches to Handle Exception
There are mainly 4 ways to handle an exception. Let's discuss each one of these approaches.
 * Extensive use of try-catch block in all error prone code.
 * Using the Global.asax block and its methods like, Application_OnError or Session_OnError. This is only applicable for web applications.
 * Error bubbling.
 * Use of Microsoft Enterprise Library.

Use of Global.asax
This is also known as Global Exception Handling. This approach traps and handles exceptions at application level. The biggest advantages of this approach is logging and notification part of the exception can be put in a single place. programming constructs in C# 3.0. Fuctions are very important sections from OOPS standpoint. In more simpler terms, a function encapsulates a block of code that can be called from other parts of the program. introduction of function increases code reusability. Literally you can tag a particular section of code with a name (funciton name) and just call that name from anywhere of your program. In C# a funciton may or may not have a return type. Functions more often are called as Methods. A funciton must be contained in a class. The basic structure of a funciton is as follows, -  { ... } Conversly to call a function you simply call it by its name with parameters, if any, within paranthesis as

follows, - DoSomething;

Passing Parameters in Function
The input parameters can be of two types, - If parameters are passed as value type then a new copy of it will be created before passing to the function.
 * Value type
 * Reference type

Whereas, for reference types only the addresses of the parameters are passed to the function. Meaning, for a value

type parameter if the function changes the parameter value then the original variable does not get changed; whereas

in case of reference type once the value gets changed in function then the original variable's value gets changed.

Here are two examples,-

(1) Value Type Function  Output  Your birth year is 1980 if your age is 30 (2) Reference Type Function  Output  Your birth year is 1980 if your age is 1980 Notice that in both the code, on line number 19 we are updating the parameter value with the calculated value. In

value type example, it is not affecting the variable. But in reference type it is changing the variable

value as well. Also for reference type parameter you must use the keyword ref while refereing to a parameter (Second

line of output).

N.B. - In both the example we can see two keywords prefixed the function BirthYear, private and

static. Private is an access-modifier and static is a keyword that specifies that the function is

directly accessible from anywhere in the code. There are many other access-modifiers in C#. These define who can

access that function or method. Here is a comprehensive list of them, -

Output Parameters
As you already learned that functions has a return type and that is the output for a function. What if you need to

have multiple outputs?

In the parameters list if you provide out keyword in front of a parameter then that becomes output parameter.

And you can add as many out parameters. Here is the structure, -  void (ref   Output 

When you are providing both the inputs,- Enter your taxable sum... 1000 Enter your tax rate... 10.2 Your Tax amount is : 102 When you are providing only taxableAmt,- Enter your taxable sum... 1000 Enter your tax rate...

Your Tax amount is : 83.3

(2) Different datatypes of parameters  Output 

When both the inputs are integers,- Enter first Value 12 Enter second Value 23 The summation is = 35 When both the inputs are strings, - Enter first Value Wiki Enter second Value versity The concatenation is : Wikiversity When data is not correct,- Enter first Value 12 Enter second Value Wikipedia Type mismatch! Operation aborted! N.B. - C# determines which function to call based upon the method's signature. If you are defining two methods

with the same name and the same number and type of passed arguments, you would get a compile-time error. That is why

Overloading is an example of compile-time polymorphism.

Run-time Polymorphism (Method Overriding)
In many occations you might face a situation where you need to modify a function of a parent class in a derived or

child class. To do this .NET provides us the functionality called Function Overriding. This is more frequently

used for the implementation of abstruct classes and interfaces. Function Overriding requires us to take note of the following keywords, -
 * virtual - Virtual function must have its implementation in the base class and may optionally be overridden in

the child class if some additional functionality is required.
 * abstruct - Abstruct function will only have its signature in the base class and must be overridden in the child

class.
 * override - Override function is the function in the child class which overrides the same signatured function

from its parent. Remember: For overriding only two access-modifiers are allowed, public or internal and both the
 * sealed - Only a overridden function can be declared sealed to stop it from any further overriding.

methods in parent as well as child should have that same.

Let's consider the following example, -

 Output  314.2 Abstruct to Override Example. child class Example of Sealed!

Notice that here we have three classes (One class is commented.). the first class ProgramBase is the base

class and like all base classes, it is abstruct. It has three methods of which one is abstruct, meaning has

only signature. ProgramChild is the child class to the programBase. It is overriding all the methods of

the base class and making one of them as sealed. In the main method it is using the methods to give us the

output. Notice that Overriding only changes the inner code block of the method in the overrided section, not the

signature. Also notice that, in AreaCalc method in ProgramChild we are calling the same method from the

base class with the base prefix. One more thing to notice here is that a public method in the base class is

a public method in the child class and same for internal. Try to change it and you will get a compile time

error. Now to the check the sealed method, just uncomment the ProgramGrandChild class and try to compile. You

will get the following error, - 'FunctionApp.ProgramGrandChild.Writer(string)': cannot override inherited member

'FunctionApp.ProgramChild.Writer(string)' because it is sealed

Function Hiding
Function Hiding or Function Shadowing is a variant of overriding. Functions of base classes, by default, are

available to the derived class. In case there is a need to not to use the function from base class then you can

subscribe to Hiding. This can be achieved using new keyword. Here is how, -  Output  314.2 child class 100 child class 100 base class Here we have two functions AreaCalc and Writer. The first one gets hidden in the child class, whereas, the

second function gets overridden in the child. In the Main function we first called both the functions through an

instance of the child class and as you can see, it executed the implementation from the child. Till here both

overriding and hiding behaved same. Now If we cast the child class instance to the parent class then things

bocome interesting. You can see that the overridden function got executed from the child; but the hidden parent

class got exposed here. As if you are executing the functions from an instance of the parent class, which is the

case for the third scenario.

Meaning, hiding does not follow inheritance rather it just creates a new version. This becomes usefull when you want

to use your base class throughout your application, not the usual use of child class. N.B.- You can do away with the new keyword and the program will still run; but be ready to get a compiler

warning as, - 'FunctionApp.ProgramChild.AreaCalc(double)' hides inherited member 'FunctionApp.ProgramBase.AreaCalc(double)'. Use

the new keyword if hiding was intended. Try to reproduce the same with the above code.

Property
This is a special type of function, which mimics the behavior of a variable.   { get;  set;} This is the simplest structure. The get or set is optional. get returns the value and set stores the

value. The beauti of it is its simplicity to use.

Further Studies
Following are some high-end stuffs related to functions. Hence, out of scope of this article.
 * Annonymous functions
 * Closures
 * Currying
 * Lambda Expressions

Practice Exercises

 * Create a program for Tower of Hanoi. Take the input of number of rings. Print out the

steps.
 * Create a program that would take two inputs and if they are texts then concatenate, but if they are numeric, it

will show the summation as result
 * Create a Tax Calculator that will calculate a person's state and federal tax based by taking inputs as follows,-

FirstName

LastName

Address

Taxable amount

And will return the tax amount. (Take predetermined values for various state tax rates).