SlideShare a Scribd company logo
1 of 19
Download to read offline
Visual C# .Net using
framework 4.5
Eng. Mahmoud Ouf
Lecture 05
mmouf@2018
Collections
Collection classes are specialized classes for data storage and retrieval.
These classes provide support for stacks, queues, lists, and hash tables. Most
collection classes implement the same interfaces.
1)ArrayList:
It represents an ordered collection of an object that can be indexed
individually.
It is basically an alternative to an array. However unlike array you can add
and remove items from a list at a specified position using an index and the
array resizes itself automatically.
It also allow dynamic memory allocation, adding, searching and sorting
items in the list.
We can Store any data type and different data type in the same ArrayList.
Arraylist belongs to System.Collection namespaces
mmouf@2018
Collections
class Program
{
static void Main(string[] args)
{
ArrayList al = new ArrayList();
Console.WriteLine("Adding some numbers:");
al.Add(45);
al.Add(78);
al.Add(9);
Console.Write("Sorted Content: ");
al.Sort();
foreach (int i in al)
{
Console.Write(i + " ");
}
}
} mmouf@2018
Collections
2)List
It is a generic class. It supports storing values of a specific type without
casting to or from object. All the data in a list are from the same data type.
List belongs to System.Collections.Generic;
List<int> list1 = new List<int>();
list1.Add(1);
int total = 0;
foreach (int num in list1 )
{
total += num;
}
mmouf@2018
Collections Initializer
It enables initialization of collections with an initialization list rather than
specific calls to Add or another method. This initialization has the same
effect as using the Add method with each collection element.
public class Person
{
string name;
List intersets = new List();
public string Name { get { return name; } set { name =value; }
public List Interests { get { return intersets; } }
}
mmouf@2018
Collections Initializer
class Test
{
static void Main(string[] args){
List PersonList = new List();
Person p1 = new Person();
p1.Name = "Ahmed";
p1.Interests.Add("Reading");
p1.Interests.Add("Running");
PersonList.Add(p1);
Person p2 = new Person();
p2.Name = "Aly";
p2.Interests.Add("Swimming");
PersonList.Add(p2);
}
} mmouf@2018
Collections Initializer
class Test
{
static void Main(string[] args)
{
var PersonList = new List{
new Person{ Name = "Ahmed", Interests = { "Reading",
"Running" } },
new Person { Name = "Aly", Interests = { "Swimming"} }};
}
}
mmouf@2018
Exception Handling
Exceptions are errors that occur in run time (Run time error), it may happen
or it may not happen
To begin to understand how to program using exception, we must first know
that exceptions are objects. All System and user-defined exceptions are
derived from System.Exception (which in turn is derived from
System.Object).
System.Object
System.Exception
System.SystemException
System.IO.IOException
System.NullReferenceException
System.OutOfMemoryException
System.ApplicationExceptionmmouf@2018
Exception Handling
The idea is to physically separate the core program statements from the error
handling statements. So, the core code that might throw exceptions are
placed in a try block and the code for handling exception is put in the catch
block.
try
{ … }
catch(exception_class obj)
{ …}
The try block is a section of code that is on the lookout for any exception
that may be encountered during the flow of execution.
If the exception occurs, the runtime stops the normal execution, terminates
the try block and start searching for a catch block that can catch the pending
exception depending on its type. mmouf@2018
Exception Handling
If the appropriate catch object is found:
It will catch the exception
It will handle the exception (execute the block of code in catch)
Continue executing the program
If the appropriate catch object is not found:
The runtime will unwind the call stack, searching for the calling
function
Re-throw the exception from this function
Search for a catch block in
and repeat till it found an appropriate catch block or reach the Main
If it happens, the exception will be considered as uncaught and raise the
default action
mmouf@2018
Exception Handling
A try block contains more than one statement. Each could raise one or more
exception object. So, the try block can raise more than one exception.
The catch block catches only one exception depending on its parameter.
Then, the try block can have multiple catch blocks.
mmouf@2018
Exception Handling
try
{
Console.WriteLine(“Enter first Number”);
int I = int.Parse(Console.ReadLine());
Console.WriteLine(“Enter second number”);
int j = int.Parse(Console.ReadLine());
int k = I / j;
}
catch(OverflowException e)
{
Console.WriteLine(e);
}
catch(DivideByZeroException e)
{
Console.WriteLine(e);
} mmouf@2018
Exception Handling
The general catch block
The general catch block, is the catch block that can catch any exception
regardless of its class. There are 2 ways to define the general catch block.
•catch
{
…………
}
•catch(System.Exception e)
{
…………
}
Any try can have only one general catch block and if it exist, it must be the
last catch.
mmouf@2018
Exception Handling
The finally statement
Sometimes, throwing an exception and unwinding the stack can create a
problem.
In the event, however, that there is some action you must take regardless of
whether an exception is thrown such as closing a file.
When finally is executed:
If the try block executes successfully, the finally block executes immediately
after the try block terminates.
If an exception occurs in the try block, the finally block executes immediately
after a catch handler completes exception handling.
If the exception is not caught by a catch handler associated with that try block
or if a catch handler associated with that try block throws an exception, the
finally block executes, then the exception is processed by the next enclosing try
block mmouf@2018
Example:
class Test
{ static int I;
private static void Welcome()
{ WriteLine(“Welcome to Our Test Class”); }
private static void GoodBye()
{ WriteLine(“This is the end of our Class”); }
public static void PrintMessage()
{ WriteLine(“This Message from Test Class”);
Welcome();
}
public static void Main()
{ I = int.Parse(Console.ReadLine());
PrintMessage();
}
}
mmouf@2018
Creating and Using Delegates
In the Last example: assume we want the PrintMessage() to call either the
Welcome() or the GoodBye() dependent on the value of I (if I < 5, call the
Welcome otherwise call GoodBye).
This means that we don’t know actually which function to be called when
the Print Message execute.
So, Here, we need to pass the function (Welcome or GoodBye) to
PrintMessage().
But, How to Pass the function?
The function itself couldn’t be passed, But, we know that the function is
loaded into the memory( have an address). So, if we can pass the address to
the function that will be great.
This is done through the Delegate which allows the programmer to
encapsulate a reference to a method inside a delegate object.
mmouf@2018
Creating and Using Delegates
public delegate void MyDelegate();
class Test
{
static int I;
private static void Welcome()
{ WriteLine(“Welcome to Our Test Class”); }
private static void GoodBye()
{ WriteLine(“This is the end of our Class”); }
public static void PrintMessage(MyDelegate m)
{
WriteLine(“This Message from Test Class”);
m();
}
mmouf@2018
Creating and Using Delegates
public static void Main()
{
I = int.Parse(Console.ReadLine());
if(I < 5)
{
MyDelegate m_Delegate = new MyDelegate(Test.Welcome);
PrintMessage(m_Delegate);
}
else
{
MyDelegate m_Delegate = new MyDelegate(Test.GoodBye);
PrintMessage(m_Delegate);
}
}
}//end class
mmouf@2018
Creating and Using Delegates
Note:
We can create a delegate object that is not attached at any function, and then we can
attach the function
We can assign more than one function to the same delegate, and when invoking this
delegate, it will execute all the functions assigned to it in the same order that it was
added.
Both are done through the += operator
We can also, delete a function from the delegate object by using the -= operator
mmouf@2018

More Related Content

What's hot (20)

Intake 37 4
Intake 37 4Intake 37 4
Intake 37 4
 
Intake 37 5
Intake 37 5Intake 37 5
Intake 37 5
 
Intake 37 6
Intake 37 6Intake 37 6
Intake 37 6
 
Intake 37 2
Intake 37 2Intake 37 2
Intake 37 2
 
Intake 38_1
Intake 38_1Intake 38_1
Intake 38_1
 
Intake 37 1
Intake 37 1Intake 37 1
Intake 37 1
 
C sharp chap5
C sharp chap5C sharp chap5
C sharp chap5
 
Intake 37 ef2
Intake 37 ef2Intake 37 ef2
Intake 37 ef2
 
C sharp chap6
C sharp chap6C sharp chap6
C sharp chap6
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
 
C sharp chap4
C sharp chap4C sharp chap4
C sharp chap4
 
C# Generics
C# GenericsC# Generics
C# Generics
 
Templates
TemplatesTemplates
Templates
 
Chapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part IChapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part I
 
Constructors destructors
Constructors destructorsConstructors destructors
Constructors destructors
 
java tutorial 3
 java tutorial 3 java tutorial 3
java tutorial 3
 
04. constructor & destructor
04. constructor & destructor04. constructor & destructor
04. constructor & destructor
 
Chapter 2 - Getting Started with Java
Chapter 2 - Getting Started with JavaChapter 2 - Getting Started with Java
Chapter 2 - Getting Started with Java
 
Basic c#
Basic c#Basic c#
Basic c#
 
C++ tutorials
C++ tutorialsC++ tutorials
C++ tutorials
 

Similar to Visual C# .Net using framework 4.5 collections and exception handling

Similar to Visual C# .Net using framework 4.5 collections and exception handling (20)

Unit iii
Unit iiiUnit iii
Unit iii
 
UNIT III.ppt
UNIT III.pptUNIT III.ppt
UNIT III.ppt
 
UNIT III (2).ppt
UNIT III (2).pptUNIT III (2).ppt
UNIT III (2).ppt
 
Collections
CollectionsCollections
Collections
 
Exceptions and errors in Java
Exceptions and errors in JavaExceptions and errors in Java
Exceptions and errors in Java
 
Java tut1
Java tut1Java tut1
Java tut1
 
Tutorial java
Tutorial javaTutorial java
Tutorial java
 
Java Tut1
Java Tut1Java Tut1
Java Tut1
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
Java 104
Java 104Java 104
Java 104
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Java căn bản - Chapter8
Java căn bản - Chapter8Java căn bản - Chapter8
Java căn bản - Chapter8
 
Chapter 8 - Exceptions and Assertions Edit summary
Chapter 8 - Exceptions and Assertions  Edit summaryChapter 8 - Exceptions and Assertions  Edit summary
Chapter 8 - Exceptions and Assertions Edit summary
 
final year project center in Coimbatore
final year project center in Coimbatorefinal year project center in Coimbatore
final year project center in Coimbatore
 
Lec2
Lec2Lec2
Lec2
 
Javase5generics
Javase5genericsJavase5generics
Javase5generics
 
Java practical
Java practicalJava practical
Java practical
 
Thread
ThreadThread
Thread
 

More from Mahmoud Ouf

More from Mahmoud Ouf (18)

Relation between classes in arabic
Relation between classes in arabicRelation between classes in arabic
Relation between classes in arabic
 
Intake 38 data access 4
Intake 38 data access 4Intake 38 data access 4
Intake 38 data access 4
 
Intake 38 data access 1
Intake 38 data access 1Intake 38 data access 1
Intake 38 data access 1
 
Intake 38 11
Intake 38 11Intake 38 11
Intake 38 11
 
Intake 38 10
Intake 38 10Intake 38 10
Intake 38 10
 
Intake 38 9
Intake 38 9Intake 38 9
Intake 38 9
 
Intake 38 8
Intake 38 8Intake 38 8
Intake 38 8
 
Intake 38 7
Intake 38 7Intake 38 7
Intake 38 7
 
Intake 37 DM
Intake 37 DMIntake 37 DM
Intake 37 DM
 
Intake 37 ef1
Intake 37 ef1Intake 37 ef1
Intake 37 ef1
 
Intake 37 linq3
Intake 37 linq3Intake 37 linq3
Intake 37 linq3
 
Intake 37 linq2
Intake 37 linq2Intake 37 linq2
Intake 37 linq2
 
Intake 37 linq1
Intake 37 linq1Intake 37 linq1
Intake 37 linq1
 
Intake 37 12
Intake 37 12Intake 37 12
Intake 37 12
 
Intake 37 11
Intake 37 11Intake 37 11
Intake 37 11
 
Intake 37 10
Intake 37 10Intake 37 10
Intake 37 10
 
Intake 37 9
Intake 37 9Intake 37 9
Intake 37 9
 
Intake 37 8
Intake 37 8Intake 37 8
Intake 37 8
 

Recently uploaded

Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 

Recently uploaded (20)

Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 

Visual C# .Net using framework 4.5 collections and exception handling

  • 1. Visual C# .Net using framework 4.5 Eng. Mahmoud Ouf Lecture 05 mmouf@2018
  • 2. Collections Collection classes are specialized classes for data storage and retrieval. These classes provide support for stacks, queues, lists, and hash tables. Most collection classes implement the same interfaces. 1)ArrayList: It represents an ordered collection of an object that can be indexed individually. It is basically an alternative to an array. However unlike array you can add and remove items from a list at a specified position using an index and the array resizes itself automatically. It also allow dynamic memory allocation, adding, searching and sorting items in the list. We can Store any data type and different data type in the same ArrayList. Arraylist belongs to System.Collection namespaces mmouf@2018
  • 3. Collections class Program { static void Main(string[] args) { ArrayList al = new ArrayList(); Console.WriteLine("Adding some numbers:"); al.Add(45); al.Add(78); al.Add(9); Console.Write("Sorted Content: "); al.Sort(); foreach (int i in al) { Console.Write(i + " "); } } } mmouf@2018
  • 4. Collections 2)List It is a generic class. It supports storing values of a specific type without casting to or from object. All the data in a list are from the same data type. List belongs to System.Collections.Generic; List<int> list1 = new List<int>(); list1.Add(1); int total = 0; foreach (int num in list1 ) { total += num; } mmouf@2018
  • 5. Collections Initializer It enables initialization of collections with an initialization list rather than specific calls to Add or another method. This initialization has the same effect as using the Add method with each collection element. public class Person { string name; List intersets = new List(); public string Name { get { return name; } set { name =value; } public List Interests { get { return intersets; } } } mmouf@2018
  • 6. Collections Initializer class Test { static void Main(string[] args){ List PersonList = new List(); Person p1 = new Person(); p1.Name = "Ahmed"; p1.Interests.Add("Reading"); p1.Interests.Add("Running"); PersonList.Add(p1); Person p2 = new Person(); p2.Name = "Aly"; p2.Interests.Add("Swimming"); PersonList.Add(p2); } } mmouf@2018
  • 7. Collections Initializer class Test { static void Main(string[] args) { var PersonList = new List{ new Person{ Name = "Ahmed", Interests = { "Reading", "Running" } }, new Person { Name = "Aly", Interests = { "Swimming"} }}; } } mmouf@2018
  • 8. Exception Handling Exceptions are errors that occur in run time (Run time error), it may happen or it may not happen To begin to understand how to program using exception, we must first know that exceptions are objects. All System and user-defined exceptions are derived from System.Exception (which in turn is derived from System.Object). System.Object System.Exception System.SystemException System.IO.IOException System.NullReferenceException System.OutOfMemoryException System.ApplicationExceptionmmouf@2018
  • 9. Exception Handling The idea is to physically separate the core program statements from the error handling statements. So, the core code that might throw exceptions are placed in a try block and the code for handling exception is put in the catch block. try { … } catch(exception_class obj) { …} The try block is a section of code that is on the lookout for any exception that may be encountered during the flow of execution. If the exception occurs, the runtime stops the normal execution, terminates the try block and start searching for a catch block that can catch the pending exception depending on its type. mmouf@2018
  • 10. Exception Handling If the appropriate catch object is found: It will catch the exception It will handle the exception (execute the block of code in catch) Continue executing the program If the appropriate catch object is not found: The runtime will unwind the call stack, searching for the calling function Re-throw the exception from this function Search for a catch block in and repeat till it found an appropriate catch block or reach the Main If it happens, the exception will be considered as uncaught and raise the default action mmouf@2018
  • 11. Exception Handling A try block contains more than one statement. Each could raise one or more exception object. So, the try block can raise more than one exception. The catch block catches only one exception depending on its parameter. Then, the try block can have multiple catch blocks. mmouf@2018
  • 12. Exception Handling try { Console.WriteLine(“Enter first Number”); int I = int.Parse(Console.ReadLine()); Console.WriteLine(“Enter second number”); int j = int.Parse(Console.ReadLine()); int k = I / j; } catch(OverflowException e) { Console.WriteLine(e); } catch(DivideByZeroException e) { Console.WriteLine(e); } mmouf@2018
  • 13. Exception Handling The general catch block The general catch block, is the catch block that can catch any exception regardless of its class. There are 2 ways to define the general catch block. •catch { ………… } •catch(System.Exception e) { ………… } Any try can have only one general catch block and if it exist, it must be the last catch. mmouf@2018
  • 14. Exception Handling The finally statement Sometimes, throwing an exception and unwinding the stack can create a problem. In the event, however, that there is some action you must take regardless of whether an exception is thrown such as closing a file. When finally is executed: If the try block executes successfully, the finally block executes immediately after the try block terminates. If an exception occurs in the try block, the finally block executes immediately after a catch handler completes exception handling. If the exception is not caught by a catch handler associated with that try block or if a catch handler associated with that try block throws an exception, the finally block executes, then the exception is processed by the next enclosing try block mmouf@2018
  • 15. Example: class Test { static int I; private static void Welcome() { WriteLine(“Welcome to Our Test Class”); } private static void GoodBye() { WriteLine(“This is the end of our Class”); } public static void PrintMessage() { WriteLine(“This Message from Test Class”); Welcome(); } public static void Main() { I = int.Parse(Console.ReadLine()); PrintMessage(); } } mmouf@2018
  • 16. Creating and Using Delegates In the Last example: assume we want the PrintMessage() to call either the Welcome() or the GoodBye() dependent on the value of I (if I < 5, call the Welcome otherwise call GoodBye). This means that we don’t know actually which function to be called when the Print Message execute. So, Here, we need to pass the function (Welcome or GoodBye) to PrintMessage(). But, How to Pass the function? The function itself couldn’t be passed, But, we know that the function is loaded into the memory( have an address). So, if we can pass the address to the function that will be great. This is done through the Delegate which allows the programmer to encapsulate a reference to a method inside a delegate object. mmouf@2018
  • 17. Creating and Using Delegates public delegate void MyDelegate(); class Test { static int I; private static void Welcome() { WriteLine(“Welcome to Our Test Class”); } private static void GoodBye() { WriteLine(“This is the end of our Class”); } public static void PrintMessage(MyDelegate m) { WriteLine(“This Message from Test Class”); m(); } mmouf@2018
  • 18. Creating and Using Delegates public static void Main() { I = int.Parse(Console.ReadLine()); if(I < 5) { MyDelegate m_Delegate = new MyDelegate(Test.Welcome); PrintMessage(m_Delegate); } else { MyDelegate m_Delegate = new MyDelegate(Test.GoodBye); PrintMessage(m_Delegate); } } }//end class mmouf@2018
  • 19. Creating and Using Delegates Note: We can create a delegate object that is not attached at any function, and then we can attach the function We can assign more than one function to the same delegate, and when invoking this delegate, it will execute all the functions assigned to it in the same order that it was added. Both are done through the += operator We can also, delete a function from the delegate object by using the -= operator mmouf@2018