You are on page 1of 18

 EXCEPTION HANDLING

 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.

 What is an exception error?

 An exception is a problem that arises during the execution of a program.

 A C# exception is a response to an exceptional situation that arises while a program


is running, such as an attempt to divide by zero.

 Exception handling

 C# exception handling is built upon four keywords:

 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.

 catch: A program catches an exception with an exception handler at the place in a


program where you want to handle the problem. The catch keyword indicates the
catching of an exception.

 finally: The finally block is used to execute a given set of statements, whether an
exception is thrown or not thrown.

 For example, if you open a file, it must be closed whether an exception is


raised or not.

 throw: A program throws an exception when a problem shows up. This is done using
a throw keyword.

 The Atoms of .NET Exception Handling

 A class type that represents the details of the exception that occurred

 A member that throws an instance of the exception class to the caller

 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.

 C# exceptions are represented by classes.

 The exception classes in C# are mainly directly or indirectly derived from the
System.Exception class.

 Some of the exception classes derived from the System.

Exception class are the System.ApplicationException and System.SystemException classes.

 The System.ApplicationException class supports exceptions generated by application


programs.

 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

public NegativeNumberException(string message)

// show message

In the new class define the following exception

if(value<0)

throw new NegativeNumberException(" Use Only Positive numbers");

Raising Exceptions

 The throw Statement

 The finally Clause

 Checking for Arithmetic Overflow

 Guidelines for Handling Exceptions


Throw Statement

a) Throw an appropriate exception


b) Give the exception a meaningful message

throw expression ;
if (minute < 1 || minute >= 60) {
throw new InvalidTimeException(minute +
" is not a valid minute");
// !! Not reached !!
}

Finally Statement

All of the statements in a finally block are always executed

Monitor.Enter(x);
try {
...}
finally {
Monitor.Exit(x);}

Checking for Arithmetic Overflow

 By default, arithmetic overflow is not checked


 A checked statement turns overflow checking on

checked {

 int number = int.MaxValue;


 Console.WriteLine(++number);

unchecked {

 int number = int.MaxValue;


 Console.WriteLine(++number);

Checked and Unchecked Statements

 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#

Why Control statements???

Flow of program defines execution path of a program. Normally a program is executed in a


sequential manner. In case you want to change the program execution flow, you can do
using control flow statements

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.

Such a situation may arise due to exception raised in program

In C# 2010, the control flow statements are dividing into three categories

a) Selection Statements

b) Iteration statements or loops

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.

C# supports two types of selection statements

1) The If statement

2) The Switch 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.

2) The Switch Statement


The switch statement allows you to compare an expression with different values. When the
expression is matched with specific value, the program control is transferred to
corresponding block of code.

The If statement

In if statement a condition or set of conditions are checked, if a condition is fulfilled, the


program control enters the if block and executes all the statements as well as instructions
defined in if block.

The general syntax is

if(statement is TRUE) EXECUTE this line of code

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

{ int age; string gender;

Console.WriteLine(“enter the age”);

age=Convert.ToInt32( Console.ReadLine());

Console.WriteLine(“enter the gender”);

Gender Console.ReadLine();

if(age>12) { if(age<18)

{ if(gender ==”male”)

{ Console.WriteLine(“You are a male child”); }

else { Console.WriteLine(“You are a girl child”);

} } else

{ Console.WriteLine(“You are an adult”);

} } else { Console.WriteLine(“You are too young”); } }}

Output is as shown below:


switch statement

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.

Iteration Statements or Loop Statements

Suppose you want to execute a set of statements 20 times in your program.

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

 An iteration statement or loop executes a statement or a set of statements in a repeated


manner.

 In C#, there are following types of iteration statements:


– While loop: Evaluates a condition before executing a loop. The loop continues
executed as long as the specified condition is true.

– 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)

Console.WriteLine(“loop will be executed 50 times”);

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;

Do { Console.WriteLine(“loop is executed 50 times”);

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.

The foreach loop works same as the for loop.

foreach(<data_type><variable_name> in <array_name>)

//statements

The description of the terms used in syntax are

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.

In: denotes a keyword that is applied after variable name.

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 delegate object holds a reference to a method with a pre-defined signature

 A signature is simply the argument list and return type of the method

 The keyword delegate specifies that we are defining a delegate object

 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

public delegate void myDelegate(int arg1,


double arg2)

 A delegate object is initialized with a (callback) method

 The method signature must match the delegate signature

public delegate void myDelegate(int arg1, double


arg2);
public class App
{
public static void Main()
{
myDelegate call = new myDelegate(aMethod);
// We can now treat call as a simple
object and pass // it around as such
}
static void aMethod(int k, double x) {}
}

In computer programming, a callback is executable code that is passed as an argument to other


code. A callback is a function that will be called when a process is done executing a specific task.
The usage of a callback is usually in asynchronous logic. To create a callback in C#, you need to store
a function address inside a variable. This is achieved using a delegate or the new lambda semantic
Function.

What is the purpose of having delegates & Events in C#?

If you understand the use of delegates,events then we can apply them in our daily projects.

/A simple C# Calculator class which will do arithmetic operations

public class Calculator

public int Add(int x, int y){}

public int Sub(int x, int y){}

public int Multi(int x, int y){}

public int Div(int x, int y){}

Our client (say console application) will use above Calculator class to do maths operations. Console
application will take two arguments

int operatorX = Convert.ToInt32(args[0]);

int operatorY = Convert.ToInt32(args[1]);

Calculator obj=new Calculator ();

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).

Add method in Calculator Class

public LCM(int x,int y){}


// And in client side

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:

Follow the below steps to create a Delegate

Declare: Declare a delegate/delegates

Define : Define a Delegate method/methods

Create : Create a Delegate objects to assign

Refer or Point : Point to reference of a Method

Invoke : Finally Call or Invoke the delegates

Delegates definition syntax

Access-modifier delegate returntype delegateName (parameters);

Access_modifier can be public, private, protected and internal.

SumDelegate” is a delegate which can refer functions which takes two integer parameters and
returns one integer.

Ex: Public delegate int SumDelegate(int x,int y);

Create a Delegate Object

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;

And in the final step invoke the delegate

objDelegate.Invoke(x,y);

 Creating Delegate Objects


 You can create delegate objects using the following syntax:
 Delegate-name object-name=new delegate-name(expression);
 Ex: Compute cmp1=new Compute(DelegateTest.Add);
 Similarly you can create another object of the Compute Delegate named
cmp2 to hold the reference of the instance of subtract method
 DelegateTest dt=new DeletegateTest();
 Compute cmp2=new Compute(dt.Subtract);
 Invoking Delegate Objects
 A delegate object can be invoked as a method is invoked.
 Syntax: Delegate-object(argument-list);
 When a delegate object is invoked, it in turn invokes the method which is
encapsulated into delegate object.

 Ex: cmp1(10,20);
cmp2(20,30);

//Define a Delegate
delegate void SumDelegate(int x,int y);

static void Main(string[] args)


{
//Declare Delegate Object
SumDelegate objDelegate= null;

//Point to method reference in our example "Sum"


objDelegate=Sum;

//Final Step Invoke Delegate


objDelegate.Invoke(10, 20);
Console.Read();
}

static void Sum(int x,int y)


{
Console.WriteLine(“ The sum is “ +(x+y).ToString());
}

Multicasting with Delegates

 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;

delegate int NumberChanger(int n);


namespace DelegateAppl
{
class TestDelegate
{
static int num = 10;
public static int AddNum(int p)
{
num = num+p;
return num;
}

public static int MultNum(int q)


{
num = num*q;
return num;
}
public static int getNum()
{
return num;
}

static void Main(string[] args)


{
//create delegate instances
NumberChanger nc1 = new NumberChanger(AddNum);
NumberChanger nc2 = new NumberChanger(MultNum);

//calling the methods using the delegate objects


nc1(25);
Console.WriteLine("Value of Num: {0}", getNum());
nc2(5);
Console.WriteLine("Value of Num: {0}", getNum());
Console.ReadKey();
}
}
}
Multicast Delegate example

using System;

delegate int NumberChanger(int n);


namespace DelegateAppl
{
class TestDelegate
{
static int num = 10;
public static int AddNum(int p)
{
num += p;
return num;
}

public static int MultNum(int q)


{
num *= q;
return num;
}

public static int getNum()


{
return num;
}

static void Main(string[] args)


{
//create delegate instances
NumberChanger nc;
NumberChanger nc1 = new NumberChanger(AddNum);
NumberChanger nc2 = new NumberChanger(MultNum);
nc = nc1;
nc += nc2;

//calling multicast
nc(5);
Console.WriteLine("Value of Num: {0}", getNum());
Console.ReadKey();
}
}
}

You might also like