SlideShare a Scribd company logo
1 of 22
[object Object],[object Object]
What is exception? Exceptions are unusual error conditions that occur during execution of a program or an application. In C#  exception handling is achieved using the try ? catch ? finally block. All the three are C# keywords that are used do exception handling. The try block encloses the statements that might throw an exception where as catch block handles any exception if one exists. The finally block can be used for doing any clean up process. try { // Statements that are can cause exception } catch(Type x) { // Statements to handle exception } finally { // Statement to clean up  }
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Showing an Error Message to User This kind of Exception Handling mechanism is the most commonly used mechanism.  try { // Code where we are anticipating the Exception } catch (Exception) { System.Windows.Forms.MessageBox.Show("Error Message: This is the Message shown to the User"); } The message shown to the user can be an error message, warning message or an Information message.
What are Custom Exceptions? Why do we need them? Custom Exceptions are exceptions that are created for applying the Business rules of the Application. These exceptions are used to implement the business rules violations of the application. For example:  The minimum balance set for Savings A/C in a bank would be different from a Current A/C. Hence, while developing the application for the same the Business rule would be kept as the same. Violation of Business Rule:  Whenever a Violation of Business rule is done, it should be notified and the proper message should be shown to the user. This will be handled by a Custom Exception. Let us illustrate the same with an example.
private void ValidateBeforeDebit(float Amount) { { if((Balance – Amount ) < MimimumBalanceNeedToHave) { throw new MimimumBalanceViolationForSavingsAccount(&quot;Current TransactionFailed: Minimum Balance not available&quot;); } Else { Debit(Amount); } } } We have a method ValidateBeforeDebit (). This method ensures the minimum balance. If there is no minimum balance then a Custom Exception of the type MimimumBalanceViolationForSavingsAccount is thrown. We need to handle the method whenever we call the method.
[object Object],[object Object],[object Object],[object Object]
   Example of handled exception: The above program can be modified in the following manner to track the exception. You can see the usage of standard  DivideByZeroException  class using System; class HandledException { public static void Main() { int x = 0; int intTemp = 0; try { intTemp = 100/x; Console.WriteLine(?Program terminated before this statement?); } catch(DivideByZeroException de) { Console.WriteLine(&quot;Division by Zero occurs&quot;);  } finally  { Console.WriteLine(&quot;Result is {0}&quot;, intTemp); } } }   
In the above example the program ends in an expected way instead of program termination. At the time of exception program control passes from exception point inside the try block and enters catch blocks. As the finally block is present, so the statements inside final block are executed. Example of exception un handled in catch block As in C#, the catch block is optional. The following program is perfectly legal in C#.  using System; class HandledException { public static void Main() { int x = 0; int intTemp = 0; try { intTemp = 100/x; Console.WriteLine(&quot;Not executed line&quot;); } finally { Console.WriteLine(&quot;Inside Finally Block&quot;); } Console.WriteLine(&quot;Result is {0}&quot;, intTemp); } }  
   The above example will produce no exception at the compilation time but the program will terminate due to un handled exception. But the thing that is of great interest to all the is that before the termination of the program the final block is executed.  Example of Multiple Catch Blocks:   A try block can throw multiple exceptions, that can handle by using multiple catch blocks. Important point here is that more specialized catch block should come before a generalized one. Otherwise the compiler will show a compilation error.  //C#: Exception Handling: Multiple catch
using System; class HandledException { public static void Main() { int x = 0; int intTemp = 0; try { intTemp = 100/x; Console.WriteLine(&quot;Not executed line&quot;); } catch(DivideByZeroException de) { Console.WriteLine(&quot;DivideByZeroException&quot; ); } catch(Exception ee) { Console.WriteLine(&quot;Exception&quot; ); }
finally { Console.WriteLine(&quot;Finally Block&quot;); } Console.WriteLine(&quot;Result is {0}&quot;, intTemp); } }  Example of Catching all Exceptions      By providing a catch block without a brackets or arguments, we can catch all exceptions occurred inside a try block. Even we can use a catch block with an Exception type parameter to catch all exceptions happened inside the try block since in C#, all exceptions are directly or indirectly inherited from the Exception class.  //C#: Exception Handling: Handling all exceptions
using System; class HandledException { public static void Main() { int x = 0; int intTemp = 0; try { intTemp = 100/x; Console.WriteLine(&quot;Not executed line&quot;); } catch { Console.WriteLine(&quot;oException&quot; ); } Console.WriteLine(&quot;Result is {0}&quot;, intTemp); } } 
The following program handles all exception with Exception object.  //C#: Exception Handling: Handling all exceptions using System; class HandledException { public static void Main() { int x = 0; int intTemp = 0; try { intTemp = 100/x; Console.WriteLine(&quot;Not executed line&quot;); } catch(Exception e) { Console.WriteLine(&quot;oException&quot; ); } Console.WriteLine(&quot;Result is {0}&quot;, intTemp); } } 
Example of Throwing an Exception: C# provides facility to throw an exception programmatically. The 'throw' keyword is used for doing the same. The general form of throwing an exception is as follows.  For example the following statement throw an ArgumentException explicitly.  throw new ArgumentException(&quot;Exception&quot;);  using System; class HandledException { public static void Main() { try { throw new DivideByZeroException(&quot;Invalid Division&quot;); } catch(DivideByZeroException e) { Console.WriteLine(&quot;Exception&quot; ); } Console.WriteLine(&quot;Final Statement that is executed&quot;); }  } 
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
User-defined Exceptions: C#, allows to create user defined exception class this class should be derived from Exception base class. So the user-defined exception classes must inherit from either Exception class or one of its standard derived classes.  //C#: Exception Handling: User defined exceptions using System; class UserDefinedException : Exception { public MyException(string str) { Console.WriteLine(&quot;User defined exception&quot;); } } class HandledException { public static void Main() { try { throw new UserDefinedException (&quot;New User Defined Exception&quot;); }
catch(Exception e) { Console.WriteLine(&quot;Exception caught here&quot; + e.ToString()); } Console.WriteLine(&quot;Final Statement that is executed &quot;); } } 
[object Object]

More Related Content

What's hot

Java exception handling
Java exception handlingJava exception handling
Java exception handlingBHUVIJAYAVELU
 
JavaScript - Chapter 6 - Basic Functions
 JavaScript - Chapter 6 - Basic Functions JavaScript - Chapter 6 - Basic Functions
JavaScript - Chapter 6 - Basic FunctionsWebStackAcademy
 
Two-dimensional array in java
Two-dimensional array in javaTwo-dimensional array in java
Two-dimensional array in javaTalha mahmood
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in JavaVadym Lotar
 
Command line-arguments-in-java-tutorial
Command line-arguments-in-java-tutorialCommand line-arguments-in-java-tutorial
Command line-arguments-in-java-tutorialKuntal Bhowmick
 
Linear Search Data Structure
Linear Search Data StructureLinear Search Data Structure
Linear Search Data StructureTalha Shaikh
 
Concurrency Control in Database Management System
Concurrency Control in Database Management SystemConcurrency Control in Database Management System
Concurrency Control in Database Management SystemJanki Shah
 
Exception handling c++
Exception handling c++Exception handling c++
Exception handling c++Jayant Dalvi
 
Java - Exception Handling
Java - Exception HandlingJava - Exception Handling
Java - Exception HandlingPrabhdeep Singh
 
VB.NET:An introduction to Namespaces in .NET framework
VB.NET:An introduction to  Namespaces in .NET frameworkVB.NET:An introduction to  Namespaces in .NET framework
VB.NET:An introduction to Namespaces in .NET frameworkRicha Handa
 
Data structure and its types
Data structure and its typesData structure and its types
Data structure and its typesNavtar Sidhu Brar
 

What's hot (20)

Exception handling
Exception handlingException handling
Exception handling
 
Nested loops
Nested loopsNested loops
Nested loops
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
JavaScript - Chapter 6 - Basic Functions
 JavaScript - Chapter 6 - Basic Functions JavaScript - Chapter 6 - Basic Functions
JavaScript - Chapter 6 - Basic Functions
 
Two-dimensional array in java
Two-dimensional array in javaTwo-dimensional array in java
Two-dimensional array in java
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in Java
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Command line-arguments-in-java-tutorial
Command line-arguments-in-java-tutorialCommand line-arguments-in-java-tutorial
Command line-arguments-in-java-tutorial
 
Linear Search Data Structure
Linear Search Data StructureLinear Search Data Structure
Linear Search Data Structure
 
Mysql joins
Mysql joinsMysql joins
Mysql joins
 
Destructors
DestructorsDestructors
Destructors
 
Vectors in Java
Vectors in JavaVectors in Java
Vectors in Java
 
Concurrency Control in Database Management System
Concurrency Control in Database Management SystemConcurrency Control in Database Management System
Concurrency Control in Database Management System
 
Exception handling c++
Exception handling c++Exception handling c++
Exception handling c++
 
Java - Exception Handling
Java - Exception HandlingJava - Exception Handling
Java - Exception Handling
 
VB.NET:An introduction to Namespaces in .NET framework
VB.NET:An introduction to  Namespaces in .NET frameworkVB.NET:An introduction to  Namespaces in .NET framework
VB.NET:An introduction to Namespaces in .NET framework
 
Data structure stack&queue basics
Data structure stack&queue   basicsData structure stack&queue   basics
Data structure stack&queue basics
 
Files and streams
Files and streamsFiles and streams
Files and streams
 
Stack
StackStack
Stack
 
Data structure and its types
Data structure and its typesData structure and its types
Data structure and its types
 

Viewers also liked (20)

Exception handling in asp.net
Exception handling in asp.netException handling in asp.net
Exception handling in asp.net
 
Error handling in ASP.NET
Error handling in ASP.NETError handling in ASP.NET
Error handling in ASP.NET
 
Asp.NET Handlers and Modules
Asp.NET Handlers and ModulesAsp.NET Handlers and Modules
Asp.NET Handlers and Modules
 
Runnable interface.34
Runnable interface.34Runnable interface.34
Runnable interface.34
 
Java exception
Java exception Java exception
Java exception
 
Access Protection
Access ProtectionAccess Protection
Access Protection
 
Effective Java - Chapter 4: Classes and Interfaces
Effective Java - Chapter 4: Classes and InterfacesEffective Java - Chapter 4: Classes and Interfaces
Effective Java - Chapter 4: Classes and Interfaces
 
Exception Handling Java
Exception Handling JavaException Handling Java
Exception Handling Java
 
Java keywords
Java keywordsJava keywords
Java keywords
 
Packages in java
Packages in javaPackages in java
Packages in java
 
Dynamic method dispatch
Dynamic method dispatchDynamic method dispatch
Dynamic method dispatch
 
Java: Exception
Java: ExceptionJava: Exception
Java: Exception
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Threads in JAVA
Threads in JAVAThreads in JAVA
Threads in JAVA
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Java exception handling ppt
Java exception handling pptJava exception handling ppt
Java exception handling ppt
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 

Similar to Exception handling

Exception Handling in C#
Exception Handling in C#Exception Handling in C#
Exception Handling in C#Abid Kohistani
 
MODULE5_EXCEPTION HANDLING.docx
MODULE5_EXCEPTION HANDLING.docxMODULE5_EXCEPTION HANDLING.docx
MODULE5_EXCEPTION HANDLING.docxVeerannaKotagi1
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingAboMohammad10
 
JP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.pptJP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.pptJAYAPRIYAR7
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaAmbigaMurugesan
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overviewBharath K
 
Lecture 09 Exception Handling(1 ) in c++.pptx
Lecture 09 Exception Handling(1 ) in c++.pptxLecture 09 Exception Handling(1 ) in c++.pptx
Lecture 09 Exception Handling(1 ) in c++.pptxZenLooper
 
Aae oop xp_13
Aae oop xp_13Aae oop xp_13
Aae oop xp_13Niit Care
 
Exception handling
Exception handlingException handling
Exception handlingWaqas Abbasi
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertionRakesh Madugula
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handlingKuntal Bhowmick
 
Exception handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread ProgrammingException handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread ProgrammingPrabu U
 
Exception Handling in C++
Exception Handling in C++Exception Handling in C++
Exception Handling in C++Deepak Tathe
 
1.4 core programming [understand error handling]
1.4 core programming [understand error handling]1.4 core programming [understand error handling]
1.4 core programming [understand error handling]tototo147
 
Exceptions
ExceptionsExceptions
Exceptionsmotthu18
 

Similar to Exception handling (20)

Exception Handling in C#
Exception Handling in C#Exception Handling in C#
Exception Handling in C#
 
MODULE5_EXCEPTION HANDLING.docx
MODULE5_EXCEPTION HANDLING.docxMODULE5_EXCEPTION HANDLING.docx
MODULE5_EXCEPTION HANDLING.docx
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
 
JP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.pptJP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.ppt
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
$Cash
$Cash$Cash
$Cash
 
$Cash
$Cash$Cash
$Cash
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
 
Java unit3
Java unit3Java unit3
Java unit3
 
F6dc1 session6 c++
F6dc1 session6 c++F6dc1 session6 c++
F6dc1 session6 c++
 
Lecture 09 Exception Handling(1 ) in c++.pptx
Lecture 09 Exception Handling(1 ) in c++.pptxLecture 09 Exception Handling(1 ) in c++.pptx
Lecture 09 Exception Handling(1 ) in c++.pptx
 
Aae oop xp_13
Aae oop xp_13Aae oop xp_13
Aae oop xp_13
 
Exception handling
Exception handlingException handling
Exception handling
 
Exceptions
ExceptionsExceptions
Exceptions
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertion
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handling
 
Exception handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread ProgrammingException handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread Programming
 
Exception Handling in C++
Exception Handling in C++Exception Handling in C++
Exception Handling in C++
 
1.4 core programming [understand error handling]
1.4 core programming [understand error handling]1.4 core programming [understand error handling]
1.4 core programming [understand error handling]
 
Exceptions
ExceptionsExceptions
Exceptions
 

More from Iblesoft

Ms sql server ii
Ms sql server  iiMs sql server  ii
Ms sql server iiIblesoft
 
MS SQL Server 1
MS SQL Server 1MS SQL Server 1
MS SQL Server 1Iblesoft
 
Master pages ppt
Master pages pptMaster pages ppt
Master pages pptIblesoft
 
State management
State managementState management
State managementIblesoft
 
State management
State managementState management
State managementIblesoft
 
Validation controls ppt
Validation controls pptValidation controls ppt
Validation controls pptIblesoft
 
Generics n delegates
Generics n delegatesGenerics n delegates
Generics n delegatesIblesoft
 
Data controls ppt
Data controls pptData controls ppt
Data controls pptIblesoft
 
Microsoft.net architecturte
Microsoft.net architecturteMicrosoft.net architecturte
Microsoft.net architecturteIblesoft
 
Asp.net architecture
Asp.net architectureAsp.net architecture
Asp.net architectureIblesoft
 
Delegates and events
Delegates and eventsDelegates and events
Delegates and eventsIblesoft
 
Javascript
JavascriptJavascript
JavascriptIblesoft
 

More from Iblesoft (17)

Ms sql server ii
Ms sql server  iiMs sql server  ii
Ms sql server ii
 
MS SQL Server 1
MS SQL Server 1MS SQL Server 1
MS SQL Server 1
 
Master pages ppt
Master pages pptMaster pages ppt
Master pages ppt
 
State management
State managementState management
State management
 
State management
State managementState management
State management
 
Validation controls ppt
Validation controls pptValidation controls ppt
Validation controls ppt
 
Controls
ControlsControls
Controls
 
Ado.net
Ado.netAdo.net
Ado.net
 
Generics n delegates
Generics n delegatesGenerics n delegates
Generics n delegates
 
Ajaxppt
AjaxpptAjaxppt
Ajaxppt
 
Data controls ppt
Data controls pptData controls ppt
Data controls ppt
 
Microsoft.net architecturte
Microsoft.net architecturteMicrosoft.net architecturte
Microsoft.net architecturte
 
Asp.net architecture
Asp.net architectureAsp.net architecture
Asp.net architecture
 
Generics
GenericsGenerics
Generics
 
Delegates and events
Delegates and eventsDelegates and events
Delegates and events
 
Javascript
JavascriptJavascript
Javascript
 
Html ppt
Html pptHtml ppt
Html ppt
 

Recently uploaded

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxPooja Bhuva
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024Elizabeth Walsh
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17Celine George
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxDr. Sarita Anand
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxUmeshTimilsina1
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxPooja Bhuva
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfDr Vijay Vishwakarma
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 

Recently uploaded (20)

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptx
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 

Exception handling

  • 1.
  • 2. What is exception? Exceptions are unusual error conditions that occur during execution of a program or an application. In C# exception handling is achieved using the try ? catch ? finally block. All the three are C# keywords that are used do exception handling. The try block encloses the statements that might throw an exception where as catch block handles any exception if one exists. The finally block can be used for doing any clean up process. try { // Statements that are can cause exception } catch(Type x) { // Statements to handle exception } finally { // Statement to clean up  }
  • 3.
  • 4.
  • 5.
  • 6.
  • 7. Showing an Error Message to User This kind of Exception Handling mechanism is the most commonly used mechanism. try { // Code where we are anticipating the Exception } catch (Exception) { System.Windows.Forms.MessageBox.Show(&quot;Error Message: This is the Message shown to the User&quot;); } The message shown to the user can be an error message, warning message or an Information message.
  • 8. What are Custom Exceptions? Why do we need them? Custom Exceptions are exceptions that are created for applying the Business rules of the Application. These exceptions are used to implement the business rules violations of the application. For example: The minimum balance set for Savings A/C in a bank would be different from a Current A/C. Hence, while developing the application for the same the Business rule would be kept as the same. Violation of Business Rule: Whenever a Violation of Business rule is done, it should be notified and the proper message should be shown to the user. This will be handled by a Custom Exception. Let us illustrate the same with an example.
  • 9. private void ValidateBeforeDebit(float Amount) { { if((Balance – Amount ) < MimimumBalanceNeedToHave) { throw new MimimumBalanceViolationForSavingsAccount(&quot;Current TransactionFailed: Minimum Balance not available&quot;); } Else { Debit(Amount); } } } We have a method ValidateBeforeDebit (). This method ensures the minimum balance. If there is no minimum balance then a Custom Exception of the type MimimumBalanceViolationForSavingsAccount is thrown. We need to handle the method whenever we call the method.
  • 10.
  • 11.   Example of handled exception: The above program can be modified in the following manner to track the exception. You can see the usage of standard DivideByZeroException class using System; class HandledException { public static void Main() { int x = 0; int intTemp = 0; try { intTemp = 100/x; Console.WriteLine(?Program terminated before this statement?); } catch(DivideByZeroException de) { Console.WriteLine(&quot;Division by Zero occurs&quot;);  } finally  { Console.WriteLine(&quot;Result is {0}&quot;, intTemp); } } }   
  • 12. In the above example the program ends in an expected way instead of program termination. At the time of exception program control passes from exception point inside the try block and enters catch blocks. As the finally block is present, so the statements inside final block are executed. Example of exception un handled in catch block As in C#, the catch block is optional. The following program is perfectly legal in C#.  using System; class HandledException { public static void Main() { int x = 0; int intTemp = 0; try { intTemp = 100/x; Console.WriteLine(&quot;Not executed line&quot;); } finally { Console.WriteLine(&quot;Inside Finally Block&quot;); } Console.WriteLine(&quot;Result is {0}&quot;, intTemp); } }  
  • 13.   The above example will produce no exception at the compilation time but the program will terminate due to un handled exception. But the thing that is of great interest to all the is that before the termination of the program the final block is executed.  Example of Multiple Catch Blocks:   A try block can throw multiple exceptions, that can handle by using multiple catch blocks. Important point here is that more specialized catch block should come before a generalized one. Otherwise the compiler will show a compilation error.  //C#: Exception Handling: Multiple catch
  • 14. using System; class HandledException { public static void Main() { int x = 0; int intTemp = 0; try { intTemp = 100/x; Console.WriteLine(&quot;Not executed line&quot;); } catch(DivideByZeroException de) { Console.WriteLine(&quot;DivideByZeroException&quot; ); } catch(Exception ee) { Console.WriteLine(&quot;Exception&quot; ); }
  • 15. finally { Console.WriteLine(&quot;Finally Block&quot;); } Console.WriteLine(&quot;Result is {0}&quot;, intTemp); } }  Example of Catching all Exceptions     By providing a catch block without a brackets or arguments, we can catch all exceptions occurred inside a try block. Even we can use a catch block with an Exception type parameter to catch all exceptions happened inside the try block since in C#, all exceptions are directly or indirectly inherited from the Exception class.  //C#: Exception Handling: Handling all exceptions
  • 16. using System; class HandledException { public static void Main() { int x = 0; int intTemp = 0; try { intTemp = 100/x; Console.WriteLine(&quot;Not executed line&quot;); } catch { Console.WriteLine(&quot;oException&quot; ); } Console.WriteLine(&quot;Result is {0}&quot;, intTemp); } } 
  • 17. The following program handles all exception with Exception object.  //C#: Exception Handling: Handling all exceptions using System; class HandledException { public static void Main() { int x = 0; int intTemp = 0; try { intTemp = 100/x; Console.WriteLine(&quot;Not executed line&quot;); } catch(Exception e) { Console.WriteLine(&quot;oException&quot; ); } Console.WriteLine(&quot;Result is {0}&quot;, intTemp); } } 
  • 18. Example of Throwing an Exception: C# provides facility to throw an exception programmatically. The 'throw' keyword is used for doing the same. The general form of throwing an exception is as follows.  For example the following statement throw an ArgumentException explicitly.  throw new ArgumentException(&quot;Exception&quot;);  using System; class HandledException { public static void Main() { try { throw new DivideByZeroException(&quot;Invalid Division&quot;); } catch(DivideByZeroException e) { Console.WriteLine(&quot;Exception&quot; ); } Console.WriteLine(&quot;Final Statement that is executed&quot;); } } 
  • 19.
  • 20. User-defined Exceptions: C#, allows to create user defined exception class this class should be derived from Exception base class. So the user-defined exception classes must inherit from either Exception class or one of its standard derived classes.  //C#: Exception Handling: User defined exceptions using System; class UserDefinedException : Exception { public MyException(string str) { Console.WriteLine(&quot;User defined exception&quot;); } } class HandledException { public static void Main() { try { throw new UserDefinedException (&quot;New User Defined Exception&quot;); }
  • 21. catch(Exception e) { Console.WriteLine(&quot;Exception caught here&quot; + e.ToString()); } Console.WriteLine(&quot;Final Statement that is executed &quot;); } } 
  • 22.