SlideShare a Scribd company logo
[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

C# Overriding
C# OverridingC# Overriding
C# Overriding
Prem Kumar Badri
 
Templates in c++
Templates in c++Templates in c++
Templates in c++
ThamizhselviKrishnam
 
Java applet
Java appletJava applet
Java applet
Rohan Gajre
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member Functions
MOHIT AGARWAL
 
Exception handling
Exception handlingException handling
Exception handling
Tata Consultancy Services
 
Inline function
Inline functionInline function
Inline functionTech_MX
 
Exception Handling
Exception HandlingException Handling
Exception Handling
Reddhi Basu
 
Presentation1
Presentation1Presentation1
Presentation1
Anul Chaudhary
 
Operators in java
Operators in javaOperators in java
Operators in java
Then Murugeshwari
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
lalithambiga kamaraj
 
Input and output in C++
Input and output in C++Input and output in C++
Input and output in C++
Nilesh Dalvi
 
Control Statements in Java
Control Statements in JavaControl Statements in Java
Control Statements in Java
Niloy Saha
 
Templates in C++
Templates in C++Templates in C++
Templates in C++Tech_MX
 
C++ Files and Streams
C++ Files and Streams C++ Files and Streams
C++ Files and Streams
Ahmed Farag
 
Clean code
Clean codeClean code
Clean code
Arturo Herrero
 
Clean code
Clean codeClean code
Clean code
Henrique Smoco
 
Control flow statements in java
Control flow statements in javaControl flow statements in java
Control flow statements in java
yugandhar vadlamudi
 

What's hot (20)

C# Overriding
C# OverridingC# Overriding
C# Overriding
 
Templates in c++
Templates in c++Templates in c++
Templates in c++
 
Java applet
Java appletJava applet
Java applet
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member Functions
 
Exception handling
Exception handlingException handling
Exception handling
 
Inline function
Inline functionInline function
Inline function
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Presentation1
Presentation1Presentation1
Presentation1
 
Characteristics of oop
Characteristics of oopCharacteristics of oop
Characteristics of oop
 
Operators in java
Operators in javaOperators in java
Operators in java
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
Operators in C++
Operators in C++Operators in C++
Operators in C++
 
Input and output in C++
Input and output in C++Input and output in C++
Input and output in C++
 
Control Statements in Java
Control Statements in JavaControl Statements in Java
Control Statements in Java
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
 
C# Delegates
C# DelegatesC# Delegates
C# Delegates
 
C++ Files and Streams
C++ Files and Streams C++ Files and Streams
C++ Files and Streams
 
Clean code
Clean codeClean code
Clean code
 
Clean code
Clean codeClean code
Clean code
 
Control flow statements in java
Control flow statements in javaControl flow statements in java
Control flow statements in java
 

Viewers also liked

Exception handling in asp.net
Exception handling in asp.netException handling in asp.net
Exception handling in asp.net
Neelesh Shukla
 
Java - Exception Handling
Java - Exception HandlingJava - Exception Handling
Java - Exception HandlingPrabhdeep Singh
 
Asp.NET Handlers and Modules
Asp.NET Handlers and ModulesAsp.NET Handlers and Modules
Asp.NET Handlers and Modules
py_sunil
 
Runnable interface.34
Runnable interface.34Runnable interface.34
Runnable interface.34myrajendra
 
Java exception
Java exception Java exception
Java exception
Arati Gadgil
 
Access Protection
Access ProtectionAccess Protection
Access Protectionmyrajendra
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in JavaVadym Lotar
 
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
İbrahim Kürce
 
Exception Handling Java
Exception Handling JavaException Handling Java
Exception Handling Java
ankitgarg_er
 
Dynamic method dispatch
Dynamic method dispatchDynamic method dispatch
Dynamic method dispatch
yugandhar vadlamudi
 
Java: Exception
Java: ExceptionJava: Exception
Java: Exception
Tareq Hasan
 
Exception handling
Exception handlingException handling
Exception handling
Abhishek Pachisia
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
Pratik Soares
 
Threads in JAVA
Threads in JAVAThreads in JAVA
Java exception handling ppt
Java exception handling pptJava exception handling ppt
Java exception handling ppt
JavabynataraJ
 
Exception handling
Exception handlingException handling
Exception handling
Raja Sekhar
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
Raja Sekhar
 

Viewers also liked (20)

Exception handling in asp.net
Exception handling in asp.netException handling in asp.net
Exception handling in asp.net
 
Java - Exception Handling
Java - Exception HandlingJava - Exception Handling
Java - Exception Handling
 
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
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in Java
 
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
 
Java exception handling ppt
Java exception handling pptJava exception handling ppt
Java exception handling ppt
 
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.docx
VeerannaKotagi1
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
AboMohammad10
 
JP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.pptJP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.ppt
JAYAPRIYAR7
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
AmbigaMurugesan
 
Exception handling
Exception handlingException handling
Exception handling
Pranali Chaudhari
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
Bharath 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++.pptx
ZenLooper
 
Aae oop xp_13
Aae oop xp_13Aae oop xp_13
Aae oop xp_13Niit Care
 
Exception handling
Exception handlingException handling
Exception handling
Waqas Abbasi
 
Exceptions
ExceptionsExceptions
Exceptions
DeepikaT13
 
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 handling
Kuntal Bhowmick
 
Exception handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread ProgrammingException handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread Programming
Prabu 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
 

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
 
Exception handling
Exception handlingException handling
Exception handling
 
$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]
 

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
Javascript
Iblesoft
 

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 Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
JosvitaDsouza2
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
Peter Windle
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
MIRIAMSALINAS13
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
DhatriParmar
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
Nguyen Thanh Tu Collection
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 

Recently uploaded (20)

The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 

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.