EXCEPTION HANDLING Notes
EXCEPTION HANDLING Notes
Bugs: This is, simply put, an error on the part of the programmer. For example, assume you
are programming with unmanaged C++. If you make calls on a NULL pointer or fail to delete
allocated memory (resulting in a memory leak), you have a bug.
User errors: Unlike bugs, user errors are typically caused by the individual running your
application, rather than by those who created it. For example, an end user who enters a mal-
formed string into a text box could very well generate an error if you fail to handle this faulty
input in your code base.
Exceptions: Exceptions are typically regarded as runtime anomalies that are difficult, if not
impossible, to account for while programming your application. Possible exceptions include
attempting to connect to a database that no longer exists, opening a corrupted file, or
contacting a machine that is currently offline. In each of these cases, the programmer (and
end user) has little control over these “exceptional” circumstances.
Exception handling
try: A try block identifies a block of code for which particular exceptions will be
activated. It's followed by one or more catch blocks.
finally: The finally block is used to execute a given set of statements, whether an
exception is thrown or not thrown.
throw: A program throws an exception when a problem shows up. This is done using
a throw keyword.
A class type that represents the details of the exception that occurred
A block of code on the caller’s side that invokes the exception-prone member
A block of code on the caller’s side that will process (or catch) the exception should
it occur
Syntax
Assuming a block will raise and exception, a method catches an exception using a
combination of the try and catch keywords.
You can list down multiple catch statements to catch different type of exceptions in case
your try block raises more than one exception in different situations.
The exception classes in C# are mainly directly or indirectly derived from the
System.Exception class.
So the exceptions defined by the programmers should derive from this class.
The System.SystemException class is the base class for all predefined system exception.
Example
1. class Program {
2. public static void division(int num1, int num2)
3. {
4. float result=0.0f;
5. try
6. {
7. result = num1 / num2;
8. }
9. catch (DivideByZeroException e)
10. {
11. Console.WriteLine("Exception Error !! \n divid by zero !!");
12. // Console.WriteLine("Exception caught: {0}", e);
13. }
14. finally
15. {
16. Console.WriteLine("Result: {0} ", result);
17. }
18. }
19. static void Main(string[] args)
20. {
21. division(10,0);
22. Console.ReadLine();
23. } }
User Defined Exception
using System;
namespace ExceptionHandling
class NegativeNumberException:ApplicationException
// show message
if(value<0)
Raising Exceptions
throw expression ;
if (minute < 1 || minute >= 60) {
throw new InvalidTimeException(minute +
" is not a valid minute");
// !! Not reached !!
}
Finally Statement
Monitor.Enter(x);
try {
...}
finally {
Monitor.Exit(x);}
checked {
unchecked {
Checked and Unchecked statements are used to check the memory overflow
exceptions.
The checked keyword is used to check the overflow for integral type arithmetic
operations and conversions.
The unchecked keyword ignores the overflow integral checking of the integral
type arithmetic.
Arithmetic overflow exceptions are raised in a checked context, in case of
unchecked context, arithmetic overflow is ignored
Control Statements in C#
The control flow statements can change program flow according to user needs and
requirements. However, sometimes it may happen that although your program is correct
and has been compiled successfully, it does not display the output according to logic.
In C# 2010, the control flow statements are dividing into three categories
a) Selection Statements
c) Jump Statements
a) Selection Statements
These statements are the statements that cause the program flow to be changed when
certain condition is fulfilled. A condition is a boolean expression, which is defined inside the
parantheses of selection statement. The condition is checked before the execution of code
block inside selection statement.
1) The If statement
1) The If statement
The If Statement allows you to test whether or not a certain condition is fulfilled. If the
condition is fulfilled, the program control is transferred to the block of code inside the If
statement, otherwise the program control is transferred another block of code.
The If statement
ex:
class Program
{
static void Main( string[ ] args)
{
int age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(“enter the age”);
age=Convert.ToInt32(Console.ReadLine());
if(age<18)
{
Console.WriteLine(“You are not eligible”);
}
else
{
Console.WriteLine(“You are eligible”);
}
Console.Read();
}
}
Nested If else statements: If statements can be nested in C#. User can test multiple
conditions using if else if statement. The syntax for nested if else statements is as
shown below:
if ( condition )
{ code to execute;
if (condition)
{ code to execute;
}
else if ( condition )
{
if ( condition )
{
code to execute;
}
}
}
class Program
age=Convert.ToInt32( Console.ReadLine());
Gender Console.ReadLine();
if(age>12) { if(age<18)
{ if(gender ==”male”)
} } else
The switch statement is used when you have to evaluate a variable for multiple values. The switch
statement construct is as shown below:
switch ( variablename )
case constantExpression_1:
statements;
break;
case constantExpression_2:
statements;
break;
case constantExpression_3:
statements;
break;
default:
statements;
break;
When the switch statement is executed, the variable name is given in the switch statement. It is
compared with each case constant. If there is a matching case statement, the control is passed to
the corresponding statement. A break statement is used to exit from the switch statement. If none
of the case matches the variable, the default statement is executed.
Instead of writing the code 20 times, you can write the code inside a loop and specify a condition to
execute the loop 20 times there by saving time and space complexity
– do..While loop: Executes the loop body at least once, before evaluating a condition.
– For loop: continues to execute the loop body until the condition specified in the loop
becomes false.
– Foreach loop: continues to execute the loop body for each element in an array or
object collection.
While Loop
While loop executes a statement or block of statements as long as Boolean expression (condition)
evaluates to true.
The while loop is used mainly in situations where you don’t know in advance how many times loop
will be executed and condition specified in while loop is checked before starting the loop.
Ex:
Int number=1;
while(number<=50)
number=number+1;
Do..While Loop
Do..While loop working is identical to while loop except in do..while loop the condition is checked at
the end of loop after each iteration.
It means that do..while loop definitely executes at least once even if the condition is false.
Ex:
Int number=1;
number=number+1;} while(number<=50);
For Loop
For loop is most important of all the loops. It works similar to while loop that the syntax of the for
loop also includes a initializer that initializes a variable and loop expression that increments or
decrements a variable value.
For loop can be applied in such situations when you know exactly how many times you want to
execute the statements.
The syntax is
for(initializer;condition;loop expression)
//statements
Initializer: specifies the initial value and it is the expression which is evaluated before the first loop is
executed.
Condition: specifies an expression that is checked before starting any new iteration of the loop.
Loop expression: specifies an expression that is evaluated after ending each iteration of the loop.
Foreach Loop
Foreach loop iterates through all items in a list. The list may be an array or collection of objects.
foreach(<data_type><variable_name> in <array_name>)
//statements
data_type: specifies data_type of a variable. The data_type of the variable and array must be same.
variable_name: represents the variable name that act as a representative for each value in item in
the array_name array.
array_name: represents the name of an array or a collection of objects which you are accessing
Delegates and Events
C# Delegate similar to functional pointer in C++ but type safe, A delegate can point to a method,
which is having same signature as that of the delegate. With the use of delegates we can call
methods asynchronously. Delegates and events can be used to implement publisher-Subscriber
models.
A signature is simply the argument list and return type of the method
For example we can define a delegate object myDelegate which holds a method
which returns void and takes an int and a double as arguments
If you understand the use of delegates,events then we can apply them in our daily projects.
Our client (say console application) will use above Calculator class to do maths operations. Console
application will take two arguments
obj.Add(operatorX,operatorY);
obj.Sub(operatorX,operatorY);
obj.Multi(operatorX,operatorY);
obj.Div(operatorX,operatorY);
The Code looks fine and it will work perfectly but if you observe carefully client (console application)
and class are tightly coupled.for example I want to calculate LCM (Least Common Multiple) of two
numbers. We will add method in Calculator class and call that method in our client (Console
application).
obj.LCM(x,y);
Both are tightly coupled that means both Class and Client needs to be compiled in order to affect the
changes.This problem can be solved with the use of Delegates.
A Simple C# Delegate:
SumDelegate” is a delegate which can refer functions which takes two integer parameters and
returns one integer.
SumDelegate objDelgate=null;
We will use the above delegate to Call sum method which will add two numbers. In third step we
have to assign delegate to reference of a method
objDelegate=Sum;
objDelegate.Invoke(x,y);
//Define a Delegate
delegate void SumDelegate(int x,int y);
Each delegate object that has been created so far holds a reference of single method.
There is possibility of delegate object to hold references of multiple methods and invoke
them.
Such delegate objects are called Multicast delegates or combinable delegates
How to encapsulate more the than one method into a single delegate object???
This is done by using overload += operator.
Objects of only those delegates that satisfy the following two conditions can be made as
multicast delegates:
The return type of delegate is void.
None of the parameters of the delegate is an output parameter.
The multicast delegates allows you to combine several delegate handlers for a given event
source into a single linked list.
The list in turn can be called either directly, under program control,or indirectly or by
triggering the events
The advantage of using Multicast Delegates is that you can modify the input to these
delegates.
The core of the Multicast Delegate is Combine() method. This method allows you to create a
chained link list of delegates to be called when the event is fired.
Delegate Examples
using System;
using System;
//calling multicast
nc(5);
Console.WriteLine("Value of Num: {0}", getNum());
Console.ReadKey();
}
}
}