Lesson 8: Exceptions catch plus other

Unity for Game Developers




Exception handling
Exception handling is a way to properly handle the execution of the code in such a manner that if the code encounters some exceptions in its execution,then  we can address it by using the keyword throw
How to check for any exception which is an unexpected behaviour ,we have to use the keywords try,catch and finally
The namespace which needs to be referenced in Exception handling is System.Exceptions namespace.
Compiler generated Exceptions are those which are automatically thrown by the CLR 

Look at the whole scenario this way

try
{ /* Put statement(s) here and try will look to see the result of my logics,expressions or calculations
*/ }
catch
{ /* Show which statement has caused the exception
e.g wrong calculations
*/ }
finally
{ /* Use logic which has to be used after the exception has been caught*/ }

 

Example1
using System.IO;
class MyClass
{
static void Main()
{
try
{
Console.WriteLine(“Enter number which has to be divided”);
int divided = int.Parse(Console.ReadLine());
Console.WriteLine(“Enter number to divide by”);
int divideby = int.Parse(Console.ReadLine());
Console.WriteLine(“The answer is : {0}”, divided / divideby);
}
catch (DivideByZeroException e)
{
Console.WriteLine(“Divide by zero exception occurred”);
}
finally
{
Console.WriteLine(“Do not enter Zero in the denominator”);
}
}
}

Output

 

The finally block  is not only specific for displaying messages.It is also used to free the space in the memory which has been allocated  since the exception is thrown. Microsoft is implementing the IDisposable interface in order to free up the memory consumed when exception is thrown. Here,the use of intPtr is implemented and clear explanation is written.Click the following link Using IDisposable,intPtr and Exception handling together  

Delegates

delegate  looks like just as a method in its declaration.They  have return type(s) and argument(s) as well.Delegates have the same signatures as the method(s)   to which they are referencing. Delegates   can be termed as pointers to functions  but unlike those in C++, they are type-safe. Delegates  may also be  generic.delegate may  point to a method  or number of  methods. >Delegates are extensively used whenever we want to use  method(s) within the methods(s). Delegates  reference  named  and  anonymous methods.Use of lambda expression(s)  is a technique to reference  delegate(s)  when they are used as parameter(s)  in method(s)

Named Methods Named methods are those which have particular names used to identify them.All the previous methods which we used so far are named-methods

Anonymous Methods >Anonymous methods are the methods without names.Point to be noted that we can not use ref  and  out  with anonymous methods.Click  at the Link to see the example.Just like   an instance of a class, an anonymous method  is created when the instance of a  delegate  is created  with the  keyword  delegate. >

Using Delegates with Named and Anonymous  Methods

Following example addresses the use of delegates to reference both the named as well as anonymous methods

 
using System;delegate void CallManyMethods(int[] argumentArray);

namespace DelegateExample
{
class MyDelegateClass
{
public  static int[] myArray=new int[5]{5,4,3,2,1};

public static void SortArray(int[] sortedArray)
{
Console.WriteLine(“nNamed method SortArray() referenced by the Delegate gives: n”);

Console.WriteLine(“Unsorted Array Elements:n”);

foreach (int a in myArray)
{
Console.WriteLine(a);

}

sortedArray = new int[5];
/*Copies the first five elements from
myArray to sortedArray */
Array.Copy(myArray, sortedArray,5);

/*Sorting the copied array*/

Array.Sort(sortedArray);

Console.WriteLine(“nSorted Array Elements:n”);
foreach (int i in sortedArray)
{
Console.WriteLine(i); ;

}

}

static void Main(string[] args)
{
//delegate instance creating anonymous mthod
CallManyMethods myDelegate = delegate(int[] o)
{
/*statement inside the body of
anonymous method  */
int[] myArray=new int[5]{5,4,3,2,1};
int[] sortedArray = new int[5];

Console.WriteLine(“Anonymous Method referenced by the Delegate gives:n”);

Console.WriteLine(“Unsorted Array Elements:n”);

foreach (int a in myArray)
{
Console.WriteLine(a);

}

Array.Copy(myArray, sortedArray,5);

Array.Sort(sortedArray);

Console.WriteLine(“nSorted Array Elements:n”);
foreach (int i in sortedArray)
{
Console.WriteLine(i); ;

}

            };//calling the delegate with anonymous method
int[] arr1=new int[5];
myDelegate(arr1);

//instiating the named method
myDelegate = new CallManyMethods(SortArray);
int[] arr2=new int[5];
// calling delegate by named method
myDelegate(arr2);

Console.ReadKey();

}
}

 

Lambda Expressions

Lambda expression is an anonymous function,with a collection of expressions and statements.It is used to create delegates  or expressional hierarchy or tree of expressions.
The lambda expression  is has the => operator named as goes to operator.
The left side of this operator has may consists of an  argument(s) list  or an  empty list.Refer this link at msdn site in order to grasp the logic
Refer Named and optional arguments feature in Visual Studio 2010 C# 4.0

Right side  of the ‘=>’  operator, on the other hand; may have statement(s) in curly brackets or expression(s).

Example
using System;
using System.Collections;
class Program
{
/* public delegate named del
returns string and takes string
as an argument*/
delegate string myDelegate(string append);

delegate void myDelegate2(string append);

static void Main()
{
/* Func is a delegate inside the namespace System
It takes one argument as an integer input and returns the type specified
by TResult parameter
calculateMudulus delegate declaration with generic
parameters of type int.Here a is the input argument/parameter
on the left side of the => and a*3 is an expression denotes
that a*3 means 3 times a.Complete description is: ‘a’ is
3 times ‘a’

*/
Func<int,int> calculateMudulus = a => a * 3;

Console.WriteLine(“‘a’ is {0}”,calculateMudulus.Invoke(50));

//Output : ‘a’ is 150

Func<int, bool> returnBool = x => x == 5;
bool result = returnBool(8);
Console.WriteLine(result);

//Output : false

myDelegate myDel = a => a + “World”;
Console.WriteLine(myDel.Invoke(“Hello “));

//Output:Hello World;

// delegate with lambda expression containing return statement
myDelegate2 myDel2 = inputParam => { string strConcat = inputParam + ” ” + “World”;
Console.WriteLine(strConcat); };
myDel2(“Hello”);

//Output:Hello World

//

Console.ReadKey();

}


}

Output

 

 

Extension Methods

It is important to have some idea about  extension methods before we move towards lambda expressions.
“Extension methods enable you to “add” methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type”.Definition taken from the website:

http://msdn.microsoft.com/en-us/library/vstudio/bb383977(v=vs.100).aspx

I am taking the examples from the above mentioned link so that I can convey to you in my own words

Examples

Example1using System;
using System.Collections;
using System.Linq; /* we have to use this class for using clauses for collections

It is known as Language Integrated Query or LINQ (pronounced as LINK).We will discuss
it later in detail */

class ExtensionMethods1
{

static void Main()
{
int[] ints = { 10, 45, 15, 39, 21, 26 };
var result = ints.OrderBy(a => a);

Console.WriteLine(“Order in ascending n”);

foreach (var i in result)
{
System.Console.Write(i + ” “);
}

Console.WriteLine(“n”);

Console.WriteLine(“Order in descending n”);

var result2 = ints.OrderByDescending(b => b);

foreach (var i in result2)
{
System.Console.Write(i + ” “);
}


Console.ReadKey();
}
}


Output

 

 

 

 

Task: Explore the last example on the given link by yourself and ask if it is required to explain.i have clearly explained you about interfaces.Use the previous knowledge to understand.

Threads

Threading is the way to boost the performance of the application.Threads are made by the programmer and it is his responsibility to apply them properly otherwise the outcomes will going to be terrible decline in program’s performance.
The use of threading in practical application can be seen as an application taking the input(s) from the user in one thread,while the other thread is waiting to perform other operations such as pay slip generation.
The thread is in context with the process of the application.A process is nothing but executing program(s) within application(s).
Threads have the ability to execute even those parts of process which are still being use by other threads.
Using Job Object is an effective way to group the processes by their attributes.these job objects
are secure,named,shared and easily managed.

Now here comes another concept about tasks.Task(s) are the core concepts inside TPL(Task Parallel Library).Tasks are often used to perform data parallelism in the execution of the programs.The data parallelism is a technique in which the data is divided into smaller parts so that each part executes in parallel in multi-processor environment,by assigning the specific portion of the data to specific processing unit.
This enhances the processing many many number of times.
It looks some what difficult to understand but clear and explanatory examples will definitely help you out
First,we will begin with threads and show you how threads can be effectively and easily implemented in our programs

ExamplesExample 1

// Threads starting and sleeping examples
using System;
using System.Threading;

public class methodsClass
{

public void methodOne()
{

Console.WriteLine(“Thread1 has been started….. “);

}

public void methodTwo()
{

Console.WriteLine(“Thread2 has been started ……”);

}

}

public class Program
{
public static void Main()
{
// creating the instance of methods class
methodsClass threadmethods = new methodsClass();

/* Creating Thread1 an Thread2 objectw, passing methodOne() and methodTwo()
methods with a ThreadStart delegate.*/

Thread Thread1 = new Thread(new ThreadStart(threadmethods.methodOne));
Thread Thread2 = new Thread(new ThreadStart(threadmethods.methodTwo));

//start first thread and invoke methodOne()
Thread1.Start();

/*keep the thread in halt for 5000 milliseconds.
After that ,it will automatically be aborted and
can’t be restarted */
Thread.Sleep(5000);

Console.WriteLine(“Thread1 has been terminated….wait for Thread2”);

Thread.Sleep(3000);

Console.Clear();

//start second thread and invoke methodTwo()
Thread2.Start();

/*keep the thread in halt for 5000 milliseconds.
After that ,it will automatically be aborted and
can’t be restarted */
Thread.Sleep(10000);

Console.ReadKey();

}
}

See the example in action

Thread joining

Thread joining is used to make the threads run in parallel without any interruption.Join is used for thread(s) to join the execution cycle.

Let’s have an example

using System;
using System.Threading;
using System.Collections;

class threadsJoin
{
public static ArrayList a;
private static void GenerateNumbers()
{
a = new ArrayList();

Console.WriteLine(“tNumbers generated by Thread1…..n”);

for (int i = 1; i <= 12; i++)
{
a.Add(i);
Console.WriteLine(“ttNumber:{0}”,a[i-1]);

}

}

private static void GenerateEvenNumbers()
{

Console.WriteLine(“nntEven numbers generated by Thread2…..n”);

for (int i = 1; i <= 12; i++)
{
if ((int)a[1]!= 0)
{

i++;

}

Console.WriteLine(“ttNumber:{0}”,a[i-1]);

}

}

static void Main()
{
try
{
Thread thread1 = new Thread(new ThreadStart(threadsJoin.GenerateNumbers));
Thread thread2 = new Thread(new ThreadStart(threadsJoin.GenerateEvenNumbers));

Console.WriteLine(“n Both threads are executing in parallel by joining togethern”);

thread1.Start();
thread2.Start();

thread1.Join();

thread2.Join();

}

catch(Exception ex)
{

Console.WriteLine(ex);
}

Console.ReadKey();
}

}

Output

 

The mutex object

The mutex object for threads works like a ticket which prevents simultaneous access of the shared resource(s) by the thread(s).
Take a simple example for the two threads performing some operations on a shared file.The thread which is reading from the file has mutex object set to non-signaled and no other thread is allowed to access this file until the mutex object state is set to signaled;which means ,the resource has been released.

Here is a link with the easiest tutorial I have found so far about mutex.You can ask in comments if there is any problem.

Mutex Example

 

ThreadPool

You may consider ThreadPool as a container for the threads which can be used when needed and aborted when the requirement is finished.
We have to make a call back(s) to the function(s) inside the the pool

What is CallBack?

According to the pretty easy definition from wikipedia(this is proper one ,I have checked :)):

Refer:http://en.wikipedia.org/wiki/Callback_(computer_programming)
In computer programming, a callback is a piece of executable code that is passed as an argument to other code, which is expected to call back (execute) the argument at some convenient time. The invocation may be immediate as in a synchronous callback or it might happen at later time, as in an asynchronous callback.
The ways that callbacks are supported in programming languages differ, but they are often implemented with subroutines, lambda expressions, blocks, or function pointers.

The wait callback is a constructor which is used to call back the method in the thread pool.The method is passed in the constructor of the wait call back when instantiating it.
The method must have its signatures.Object is the class present for WaitCallbaCK.
The WaitCallback is basically a delegate or the pointer to the method inside the thread pool

Let’s see the real action scene

Example

using System;
using System.Threading;
public class Example
{
public static void Main()
{

Console.Clear();
//Queing the two methods inside the ThreadPool

ThreadPool.QueueUserWorkItem(new WaitCallback(Process1));
ThreadPool.QueueUserWorkItem(new WaitCallback(Process2));

Console.WriteLine(“As Main() method is the entry point.It is invoked first”);

Thread.Sleep(1000);

Console.WriteLine(“nMain Method has completed its execution.”);

Console.ReadKey();

}

// This thread procedure performs the task.
static void Process1(Object greetings)
{
// No state object was passed to QueueUserWorkItem, so
// stateInfo is null.
Console.WriteLine(“nGreetings! Process1 is the first process to get executed after Main().”);
}

static void Process2(Object greetings)
{

Console.WriteLine(“nGreetings! Process2 is the second process to get executed after Main().”);

}

}

Tasks

A task is simply an asynchronous operation.Threads perform these tasks in order to distribute the
in chunks for faster execution.

Synchronous and Asynchronous Operations in .Net 4.0

using System;
using System.Threading;

namespace Tasks
{

class Program
{

public static void Greetings()
{

Console.Write(” a”);
Thread.Sleep(1000);
}

static void Main()
{
/* an instance of Thread class is created
* which is pointin to the method Greetings
Note:The method Greetings is not yet executing

*/
var task = new Thread(Greetings);

string[] str = new string[] { “Have”, ” nice”, ” day” };

/* here we are invoking the method Greetings
but since the method Main() always executes first
the control goes to the next lines in Main() to execute them
first.After the first invoke of Main() has been made,the next line
will start the task which is pointing to the method Greetings().Greetings()
is invoked and run only once to write “a” it task 1000 miliseconds to complete its operation
and after that,the remaining lines of Main() method will be executed.The Sleep()is used to halt the Main()
for further execution for the time period of 1000 ms for Greetings() method to finish its execution
*/

task.Start();

for (var i = 0; i

Output

    Have a nice day

Events
An event is raised when there is some change in the objects in a class in C#.It is the way to notify the user that a particular change has happened as a result of particular action performed to an object.Events  have significant importance when we are using C# in graphical interfaces such as windows form applications.Events  are not only limited to be used within the graphical interfaces.They provide the functionality to indicate the user that some change has occurred in the object.An event is always used with a delegate.The EventHandler in .Net platform is a seriously typed delegate,which holds the pointer to that method that handles an event.These concepts are looking tough but example will certainly clarify your confusions

Example

using System;
using System.Threading;

namespace Events
{

delegate void MyEventsInvoker();

class Program
{

/*

This is an Event of type delegate ‘MyEventsInvoker’ which will include
* pointer to the Methods as arguments which we want to invoke
* from myEvent.Invoke() method.This is really an awesome approach when we shall be
* developing forms based applications as well as web based applications.
* This concept is amongst the key features.
*

*/
public static event MyEventsInvoker myEvent;

//Heart of all the methods in C#
static void Main()
{
//Adding event handlers pointing towards the different methods

myEvent += new MyEventsInvoker(Fibonacci);
myEvent += new MyEventsInvoker(Trianlgle);
// Invoke the event.
myEvent.Invoke();

Console.ReadKey();
}

static void Trianlgle()
{

Console.WriteLine(“nHow about the triangle of asteriksn”);

for (int i = 0; i <= 5; i++) { for (int k = 1; k <= 5 - i; k++) { Console.Write(" "); } for (int j = 0; j < i; j++) { Console.Write(" * "); } Console.Write("n"); } } static void Fibonacci( ) { Console.WriteLine("Fibonacci Series for first 25 integersn"); int start = 0; int increment = 1; for (int i = 0; i <25; i++) { int buff = start; start = increment; increment = buff + increment; Console.WriteLine(start); } } } }

Output

Lesson 8 completed…

Copyrighted.com Registered & Protected 
4O71-NLVA-SUNX-ISDG


Syed Adeel Ahmed
Analyst, Programmer, Educationist and Blogger at Technofranchise
Computer Systems Engineer from Sir Syed University Of Engineering & Technology.I am passionate about all types of programming.
Syed Adeel Ahmed on FacebookSyed Adeel Ahmed on GoogleSyed Adeel Ahmed on InstagramSyed Adeel Ahmed on Twitter

Published by

Syed Adeel Ahmed

Computer Systems Engineer from Sir Syed University Of Engineering & Technology.I am passionate about all types of programming.