SlideShare a Scribd company logo
EXCEPTION HANDLING
Handling Errors during the Program
Execution
What are Exceptions?
Handling Exceptions
The System.Exception Class
Types of Exceptions and their Hierarchy
Raising (Throwing) Exceptions
Best Practices
2
WHAT ARE EXCEPTIONS?
The exceptions in .NET Framework are classic
implementation of the OOP exception model
Deliver powerful mechanism for centralized handling of
errors and unusual events
Substitute procedure-oriented approach,
in which each function returns error code
Simplify code construction and maintenance
Allow the problematic situations to be
processed at multiple levels
3
HANDLING EXCEPTIONS
In C# the exceptions can be handled by the try-
catch-finally construction
catch blocks can be used multiple times to
process different exception types
4
try
{
// Do some work that can raise an exception
}
catch (DivideByZeroException ex)
{
// Handle the caught DivideByZeroException ex
}
Catch (Exeption ex)
{
// Handle the caught Exception ex
}
HANDLING EXCEPTIONS –
EXAMPLE
5
static void Main()
{
string s = Console.ReadLine();
try
{
Int32.Parse(s);
Console.WriteLine(
"You entered valid Int32 number {0}.", s);
}
catch (FormatException)
{
Console.WriteLine("Invalid integer number!");
}
catch (OverflowException)
{
Console.WriteLine(
"The number is too big to fit in Int32!");
}
}
THE SYSTEM.EXCEPTION
CLASS
Exception is a base class for all exceptions
Important properties:
Message – user-oriented message about error
Source – name of an error source (application or object)
InnerException – inner exception (if called from other)
StackTrace – call stack to the point of exception call
TargetSite – method name which raised an exception
HelpLink – URL-address to information about exception
Data – dictionary with additional information with exception
(IDictionary)
6
EXCEPTION PROPERTIES –
EXAMPLE
7
class ExceptionsExample
{
public static void CauseFormatException()
{
string s = "an invalid number";
Int32.Parse(s);
}
static void Main()
{
try
{
CauseFormatException();
}
catch (FormatException fe)
{
Console.Error.WriteLine("Exception: {0}n{1}",
fe.Message, fe.StackTrace);
}
}
}
EXCEPTION PROPERTIES
The Message property gives brief
description of the problem
The StackTrace property is extremely
useful when identifying the reason
caused the exception
8
Exception caught: Input string was not in a correct
format.
at System.Number.ParseInt32(String s, NumberStyles
style, NumberFormatInfo info)
at System.Int32.Parse(String s)
at ExceptionsTest.CauseFormatException() in
c:consoleapplication1exceptionstest.cs:line 8
at ExceptionsTest.Main(String[] args) in
c:consoleapplication1exceptionstest.cs:line 15
EXCEPTION PROPERTIES (2)
File names and line numbers are
accessible only if the compilation was in
Debug mode
When compiled in Release mode, the
information in the property StackTrace
is quite different:
9
Exception caught: Input string was not in a correct
format.
at System.Number.ParseInt32(String s, NumberStyles
style, NumberFormatInfo info)
at ExceptionsTest.Main(String[] args)
EXCEPTION HIERARCHY
Exceptions in .NET Framework are organized in a
hierarchy
10
TYPES OF EXCEPTIONS
.NET exceptions inherit from System.Exception
The system exceptions inherit from
System.SystemException, e.g.
 System.ArgumentException
 System.NullReferenceException
 System.OutOfMemoryException
 System.StackOverflowException
User-defined exceptions should inherit from
System.ApplicationException
11
HANDLING EXCEPTIONS
When catching an exception of a particular class, all
its inheritors (child exceptions) are caught too
Example:
Handles ArithmeticException and its descendants
DivideByZeroException and OverflowException
12
try
{
// Do some works that can cause an exception
}
catch (System.ArithmeticException)
{
// Handle the caught arithmetic exception
}
FIND THE MISTAKE!
13
static void Main()
{
string s = Console.ReadLine();
try
{
Int32.Parse(s);
}
catch (Exception)
{
Console.WriteLine("Can not parse the number!");
}
catch (FormatException)
{
Console.WriteLine("Invalid integer number!");
}
catch (OverflowException)
{
Console.WriteLine(
"The number is too big to fit in Int32!");
}
}
This should be
last
Unreachable
code
Unreachable
code
HANDLING ALL EXCEPTIONS
All exceptions thrown by .NET managed code
inherit the System.Exception exception
Unmanaged code can throw other exceptions
For handling all exceptions (even unmanaged)
use the construction:
14
try
{
// Do some works that can raise any exception
}
catch
{
// Handle the caught exception
}
THROWING EXCEPTIONS
Exceptions are thrown (raised) by throw keyword in C#
 Used to notify the calling code in case of error or unusual
situation
When an exception is thrown:
 The program execution stops
 The exception travels over the stack until a suitable catch block
is reached to handle it
Unhandled exceptions display
error message
15
HOW EXCEPTIONS WORK?
16
Main()
Method 1
Method 2
Method N
2. Method call
3. Method call
4. Method call
…
Main()
Method 1
Method 2
Method N
8. Find handler
7. Find handler
6. Find handler
…
5. Throw an exception
.NET
CLR
USING THROW KEYWORD
Throwing an exception with an error message:
Exceptions can accept message and cause:
Note: if the original exception is not passed the initial cause of
the exception is lost
17
throw new ArgumentException("Invalid amount!");
try
{
Int32.Parse(str);
}
catch (FormatException fe)
{
throw new ArgumentException("Invalid number", fe);
}
RE-THROWING EXCEPTIONS
Caught exceptions can be re-thrown again:
18
try
{
Int32.Parse(str);
}
catch (FormatException fe)
{
Console.WriteLine("Parse failed!");
throw fe; // Re-throw the caught exception
}
catch (FormatException)
{
throw; // Re-throws the last caught exception
}
THROWING EXCEPTIONS –
EXAMPLE
19
public static double Sqrt(double value)
{
if (value < 0)
throw new System.ArgumentOutOfRangeException(
"Sqrt for negative numbers is undefined!");
return Math.Sqrt(value);
}
static void Main()
{
try
{
Sqrt(-1);
}
catch (ArgumentOutOfRangeException ex)
{
Console.Error.WriteLine("Error: " + ex.Message);
throw;
}
}
CHOOSING THE EXCEPTION
TYPE
When an invalid parameter is passed to a
method:
 ArgumentException, ArgumentNullException,
ArgumentOutOfRangeException
When requested operation is not supported
 NotSupportedException
When a method is still not implemented
 NotImplementedException
If no suitable standard exception class is
available
 Create own exception class (inherit Exception)
20
THE TRY-FINALLY STATEMENT
The statement:
Ensures execution of given block in all cases
 When exception is raised or not in the try block
Used for execution of cleaning-up code, e.g. releasing
resources
21
try
{
// Do some work that can cause an exception
}
finally
{
// This block will always execute
}
TRY-FINALLY – EXAMPLE
22
static void TestTryFinally()
{
Console.WriteLine("Code executed before try-finally.");
try
{
string str = Console.ReadLine();
Int32.Parse(str);
Console.WriteLine("Parsing was successful.");
return; // Exit from the current method
}
catch (FormatException)
{
Console.WriteLine("Parsing failed!");
}
finally
{
Console.WriteLine(
"This cleanup code is always executed.");
}
Console.WriteLine(
"This code is after the try-finally block.");
}
EXCEPTIONS – BEST
PRACTICES
catch blocks should begin with the exceptions lowest
in the hierarchy
 And continue with the more general exceptions
 Otherwise a compilation error will occur
Each catch block should handle only these exceptions
which it expects
 If a method is not competent to handle an exception, it should
be left unhandled
 Handling all exceptions disregarding their type is popular bad
practice (anti-pattern)!
23
EXCEPTIONS – BEST PRACTICES
(2)
When raising an exception always pass to the
constructor good explanation message
When throwing an exception always pass a
good description of the problem
 Exception message should explain what causes the
problem and how to solve it
 Good: "Size should be integer in range [1…15]"
 Good: "Invalid state. First call Initialize()"
 Bad: "Unexpected error"
 Bad: "Invalid argument"
24
EXCEPTIONS – BEST
PRACTICES (3)
Exceptions can decrease the application
performance
 Throw exceptions only in situations which are
really exceptional and should be handled
 Do not throw exceptions in the normal program
control flow (e.g. for invalid user input)
CLR could throw exceptions at any time with
no way to predict them
 E.g. System.OutOfMemoryException
25
SUMMARY
Exceptions provide flexible error handling
mechanism in .NET Framework
 Allow errors to be handled at multiple levels
 Each exception handler processes only errors of
particular type (and its child types)
 Other types of errors are processed by some other handlers later
 Unhandled exceptions cause error messages
Try-finally ensures given code block is always
executed (even when an exception is thrown)
26

More Related Content

Similar to Exception Handlin g C#.pptx

JP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.pptJP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.ppt
JAYAPRIYAR7
 
Exception_Handling.pptx
Exception_Handling.pptxException_Handling.pptx
Exception_Handling.pptx
AsisKumarTripathy
 
Java exception handling
Java exception handlingJava exception handling
Java exception handlingBHUVIJAYAVELU
 
Exception handling
Exception handlingException handling
Exception handling
Karthik Sekar
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
AboMohammad10
 
Exception handling
Exception handlingException handling
Exception handling
Raja Sekhar
 
Exception handlingpdf
Exception handlingpdfException handlingpdf
Exception handlingpdf
gandra jeeshitha
 
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
 
Week7 exception handling
Week7 exception handlingWeek7 exception handling
Week7 exception handlingAlpesh Oza
 
Week7 exception handling
Week7 exception handlingWeek7 exception handling
Week7 exception handlingAlpesh Oza
 
Week7 exception handling
Week7 exception handlingWeek7 exception handling
Week7 exception handling
Alpesh Oza
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
gopalrajput11
 
Exception handling
Exception handlingException handling
Exception handlingIblesoft
 
Csphtp1 11
Csphtp1 11Csphtp1 11
Csphtp1 11
HUST
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
Md. Tanvir Hossain
 

Similar to Exception Handlin g C#.pptx (20)

JP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.pptJP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.ppt
 
Exception_Handling.pptx
Exception_Handling.pptxException_Handling.pptx
Exception_Handling.pptx
 
Comp102 lec 10
Comp102   lec 10Comp102   lec 10
Comp102 lec 10
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
java exception.pptx
java exception.pptxjava exception.pptx
java exception.pptx
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handlingpdf
Exception handlingpdfException handlingpdf
Exception handlingpdf
 
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
 
Week7 exception handling
Week7 exception handlingWeek7 exception handling
Week7 exception handling
 
Week7 exception handling
Week7 exception handlingWeek7 exception handling
Week7 exception handling
 
Week7 exception handling
Week7 exception handlingWeek7 exception handling
Week7 exception handling
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling
Exception handlingException handling
Exception handling
 
Csphtp1 11
Csphtp1 11Csphtp1 11
Csphtp1 11
 
$Cash
$Cash$Cash
$Cash
 
$Cash
$Cash$Cash
$Cash
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Java unit3
Java unit3Java unit3
Java unit3
 

Recently uploaded

Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Teleport Manpower Consultant
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
AJAYKUMARPUND1
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
Neometrix_Engineering_Pvt_Ltd
 
Investor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptxInvestor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptx
AmarGB2
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
gerogepatton
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
Osamah Alsalih
 
Architectural Portfolio Sean Lockwood
Architectural Portfolio Sean LockwoodArchitectural Portfolio Sean Lockwood
Architectural Portfolio Sean Lockwood
seandesed
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
karthi keyan
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
Kamal Acharya
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation & Control
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
Kamal Acharya
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Sreedhar Chowdam
 
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
bakpo1
 
The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
ankuprajapati0525
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
manasideore6
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
SamSarthak3
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
Pipe Restoration Solutions
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
zwunae
 
ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
Jayaprasanna4
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
thanhdowork
 

Recently uploaded (20)

Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
 
Investor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptxInvestor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptx
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
 
Architectural Portfolio Sean Lockwood
Architectural Portfolio Sean LockwoodArchitectural Portfolio Sean Lockwood
Architectural Portfolio Sean Lockwood
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
 
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
 
The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
 
ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
 

Exception Handlin g C#.pptx

  • 1. EXCEPTION HANDLING Handling Errors during the Program Execution
  • 2. What are Exceptions? Handling Exceptions The System.Exception Class Types of Exceptions and their Hierarchy Raising (Throwing) Exceptions Best Practices 2
  • 3. WHAT ARE EXCEPTIONS? The exceptions in .NET Framework are classic implementation of the OOP exception model Deliver powerful mechanism for centralized handling of errors and unusual events Substitute procedure-oriented approach, in which each function returns error code Simplify code construction and maintenance Allow the problematic situations to be processed at multiple levels 3
  • 4. HANDLING EXCEPTIONS In C# the exceptions can be handled by the try- catch-finally construction catch blocks can be used multiple times to process different exception types 4 try { // Do some work that can raise an exception } catch (DivideByZeroException ex) { // Handle the caught DivideByZeroException ex } Catch (Exeption ex) { // Handle the caught Exception ex }
  • 5. HANDLING EXCEPTIONS – EXAMPLE 5 static void Main() { string s = Console.ReadLine(); try { Int32.Parse(s); Console.WriteLine( "You entered valid Int32 number {0}.", s); } catch (FormatException) { Console.WriteLine("Invalid integer number!"); } catch (OverflowException) { Console.WriteLine( "The number is too big to fit in Int32!"); } }
  • 6. THE SYSTEM.EXCEPTION CLASS Exception is a base class for all exceptions Important properties: Message – user-oriented message about error Source – name of an error source (application or object) InnerException – inner exception (if called from other) StackTrace – call stack to the point of exception call TargetSite – method name which raised an exception HelpLink – URL-address to information about exception Data – dictionary with additional information with exception (IDictionary) 6
  • 7. EXCEPTION PROPERTIES – EXAMPLE 7 class ExceptionsExample { public static void CauseFormatException() { string s = "an invalid number"; Int32.Parse(s); } static void Main() { try { CauseFormatException(); } catch (FormatException fe) { Console.Error.WriteLine("Exception: {0}n{1}", fe.Message, fe.StackTrace); } } }
  • 8. EXCEPTION PROPERTIES The Message property gives brief description of the problem The StackTrace property is extremely useful when identifying the reason caused the exception 8 Exception caught: Input string was not in a correct format. at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at System.Int32.Parse(String s) at ExceptionsTest.CauseFormatException() in c:consoleapplication1exceptionstest.cs:line 8 at ExceptionsTest.Main(String[] args) in c:consoleapplication1exceptionstest.cs:line 15
  • 9. EXCEPTION PROPERTIES (2) File names and line numbers are accessible only if the compilation was in Debug mode When compiled in Release mode, the information in the property StackTrace is quite different: 9 Exception caught: Input string was not in a correct format. at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at ExceptionsTest.Main(String[] args)
  • 10. EXCEPTION HIERARCHY Exceptions in .NET Framework are organized in a hierarchy 10
  • 11. TYPES OF EXCEPTIONS .NET exceptions inherit from System.Exception The system exceptions inherit from System.SystemException, e.g.  System.ArgumentException  System.NullReferenceException  System.OutOfMemoryException  System.StackOverflowException User-defined exceptions should inherit from System.ApplicationException 11
  • 12. HANDLING EXCEPTIONS When catching an exception of a particular class, all its inheritors (child exceptions) are caught too Example: Handles ArithmeticException and its descendants DivideByZeroException and OverflowException 12 try { // Do some works that can cause an exception } catch (System.ArithmeticException) { // Handle the caught arithmetic exception }
  • 13. FIND THE MISTAKE! 13 static void Main() { string s = Console.ReadLine(); try { Int32.Parse(s); } catch (Exception) { Console.WriteLine("Can not parse the number!"); } catch (FormatException) { Console.WriteLine("Invalid integer number!"); } catch (OverflowException) { Console.WriteLine( "The number is too big to fit in Int32!"); } } This should be last Unreachable code Unreachable code
  • 14. HANDLING ALL EXCEPTIONS All exceptions thrown by .NET managed code inherit the System.Exception exception Unmanaged code can throw other exceptions For handling all exceptions (even unmanaged) use the construction: 14 try { // Do some works that can raise any exception } catch { // Handle the caught exception }
  • 15. THROWING EXCEPTIONS Exceptions are thrown (raised) by throw keyword in C#  Used to notify the calling code in case of error or unusual situation When an exception is thrown:  The program execution stops  The exception travels over the stack until a suitable catch block is reached to handle it Unhandled exceptions display error message 15
  • 16. HOW EXCEPTIONS WORK? 16 Main() Method 1 Method 2 Method N 2. Method call 3. Method call 4. Method call … Main() Method 1 Method 2 Method N 8. Find handler 7. Find handler 6. Find handler … 5. Throw an exception .NET CLR
  • 17. USING THROW KEYWORD Throwing an exception with an error message: Exceptions can accept message and cause: Note: if the original exception is not passed the initial cause of the exception is lost 17 throw new ArgumentException("Invalid amount!"); try { Int32.Parse(str); } catch (FormatException fe) { throw new ArgumentException("Invalid number", fe); }
  • 18. RE-THROWING EXCEPTIONS Caught exceptions can be re-thrown again: 18 try { Int32.Parse(str); } catch (FormatException fe) { Console.WriteLine("Parse failed!"); throw fe; // Re-throw the caught exception } catch (FormatException) { throw; // Re-throws the last caught exception }
  • 19. THROWING EXCEPTIONS – EXAMPLE 19 public static double Sqrt(double value) { if (value < 0) throw new System.ArgumentOutOfRangeException( "Sqrt for negative numbers is undefined!"); return Math.Sqrt(value); } static void Main() { try { Sqrt(-1); } catch (ArgumentOutOfRangeException ex) { Console.Error.WriteLine("Error: " + ex.Message); throw; } }
  • 20. CHOOSING THE EXCEPTION TYPE When an invalid parameter is passed to a method:  ArgumentException, ArgumentNullException, ArgumentOutOfRangeException When requested operation is not supported  NotSupportedException When a method is still not implemented  NotImplementedException If no suitable standard exception class is available  Create own exception class (inherit Exception) 20
  • 21. THE TRY-FINALLY STATEMENT The statement: Ensures execution of given block in all cases  When exception is raised or not in the try block Used for execution of cleaning-up code, e.g. releasing resources 21 try { // Do some work that can cause an exception } finally { // This block will always execute }
  • 22. TRY-FINALLY – EXAMPLE 22 static void TestTryFinally() { Console.WriteLine("Code executed before try-finally."); try { string str = Console.ReadLine(); Int32.Parse(str); Console.WriteLine("Parsing was successful."); return; // Exit from the current method } catch (FormatException) { Console.WriteLine("Parsing failed!"); } finally { Console.WriteLine( "This cleanup code is always executed."); } Console.WriteLine( "This code is after the try-finally block."); }
  • 23. EXCEPTIONS – BEST PRACTICES catch blocks should begin with the exceptions lowest in the hierarchy  And continue with the more general exceptions  Otherwise a compilation error will occur Each catch block should handle only these exceptions which it expects  If a method is not competent to handle an exception, it should be left unhandled  Handling all exceptions disregarding their type is popular bad practice (anti-pattern)! 23
  • 24. EXCEPTIONS – BEST PRACTICES (2) When raising an exception always pass to the constructor good explanation message When throwing an exception always pass a good description of the problem  Exception message should explain what causes the problem and how to solve it  Good: "Size should be integer in range [1…15]"  Good: "Invalid state. First call Initialize()"  Bad: "Unexpected error"  Bad: "Invalid argument" 24
  • 25. EXCEPTIONS – BEST PRACTICES (3) Exceptions can decrease the application performance  Throw exceptions only in situations which are really exceptional and should be handled  Do not throw exceptions in the normal program control flow (e.g. for invalid user input) CLR could throw exceptions at any time with no way to predict them  E.g. System.OutOfMemoryException 25
  • 26. SUMMARY Exceptions provide flexible error handling mechanism in .NET Framework  Allow errors to be handled at multiple levels  Each exception handler processes only errors of particular type (and its child types)  Other types of errors are processed by some other handlers later  Unhandled exceptions cause error messages Try-finally ensures given code block is always executed (even when an exception is thrown) 26

Editor's Notes

  1. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  2. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  3. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  4. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  5. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  6. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  7. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  8. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  9. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  10. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  11. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  12. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  13. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  14. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  15. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  16. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  17. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  18. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*