SlideShare a Scribd company logo
Exceptions HandlingExceptions Handling
Handling Errors during the Program ExecutionHandling Errors during the Program Execution
Svetlin NakovSvetlin Nakov
Telerik CorporationTelerik Corporation
www.telerik.comwww.telerik.com
Table of ContentsTable of Contents
1.1. What are Exceptions?What are Exceptions?
2.2. Handling ExceptionsHandling Exceptions
3.3. TheThe System.ExceptionSystem.Exception ClassClass
4.4. Types of Exceptions and theirTypes of Exceptions and their
HierarchyHierarchy
5.5. RaisingRaising ((ThrowingThrowing)) ExceptionsExceptions
6.6. Best PracticesBest Practices
2
What are Exceptions?What are Exceptions?
The Paradigm of Exceptions in OOPThe Paradigm of Exceptions in OOP
What are Exceptions?What are Exceptions?
 The exceptions in .NET Framework are classicThe exceptions in .NET Framework are classic
implementation of the OOP exception modelimplementation of the OOP exception model
 Deliver powerful mechanism for centralizedDeliver powerful mechanism for centralized
handling of errors and unusual eventshandling of errors and unusual events
 Substitute procedure-oriented approach,Substitute procedure-oriented approach,
in which each function returns error codein which each function returns error code
 Simplify code construction and maintenanceSimplify code construction and maintenance
 Allow the problematic situations to beAllow the problematic situations to be
processed at multiple levelsprocessed at multiple levels
4
Handling ExceptionsHandling Exceptions
Catching and Processing ErrorsCatching and Processing Errors
Handling ExceptionsHandling Exceptions
 In C# the exceptions can be handled by theIn C# the exceptions can be handled by the
try-catch-finallytry-catch-finally constructionconstruction
 catchcatch blocks can be used multiple times toblocks can be used multiple times to
process different exception typesprocess different exception types
trytry
{{
// Do some work that can raise an exception// Do some work that can raise an exception
}}
catch (SomeException)catch (SomeException)
{{
// Handle the caught exception// Handle the caught exception
}}
6
Handling Exceptions – ExampleHandling Exceptions – Example
static void Main()static void Main()
{{
string s = Console.ReadLine();string s = Console.ReadLine();
trytry
{{
Int32.Parse(s);Int32.Parse(s);
Console.WriteLine(Console.WriteLine(
"You entered valid Int32 number {0}.", s);"You entered valid Int32 number {0}.", s);
}}
catchcatch (FormatException)(FormatException)
{{
Console.WriteLine("Invalid integer number!");Console.WriteLine("Invalid integer number!");
}}
catchcatch (OverflowException)(OverflowException)
{{
Console.WriteLine(Console.WriteLine(
"The number is too big to fit in Int32!");"The number is too big to fit in Int32!");
}}
}}
7
HandlingHandling
ExceptionsExceptions
Live DemoLive Demo
TheThe System.ExceptionSystem.Exception ClassClass
 Exceptions inExceptions in .NET.NET are objectsare objects
 TheThe System.ExceptionSystem.Exception class is base for allclass is base for all
exceptions in CLRexceptions in CLR
 Contains information for the cause of the error orContains information for the cause of the error or
the unusual situationthe unusual situation
 MessageMessage –– text description of the exceptiontext description of the exception
 StackTraceStackTrace –– the snapshot of the stack at thethe snapshot of the stack at the
moment of exception throwingmoment of exception throwing
 InnerExceptionInnerException –– exception caused the currentexception caused the current
exceptionexception ((if anyif any))
9
Exception Properties – ExampleException Properties – Example
class ExceptionsTestclass ExceptionsTest
{{
public static void CauseFormatException()public static void CauseFormatException()
{{
string s = "an invalid number";string s = "an invalid number";
Int32.Parse(s);Int32.Parse(s);
}}
static void Main()static void Main()
{{
trytry
{{
CauseFormatException();CauseFormatException();
}}
catch (FormatException fe)catch (FormatException fe)
{{
Console.Error.WriteLine("Exception caught: {0}n{1}",Console.Error.WriteLine("Exception caught: {0}n{1}",
fe.Message, fe.StackTrace);fe.Message, fe.StackTrace);
}}
}}
}}
10
Exception PropertiesException Properties
 TheThe MessageMessage property gives brief description of theproperty gives brief description of the
problemproblem
 TheThe StackTraceStackTrace property is extremely useful whenproperty is extremely useful when
identifying the reason caused the exceptionidentifying the reason caused the exception
Exception caught: Input string was not in a correctException caught: Input string was not in a correct
format.format.
at System.Number.ParseInt32(String s, NumberStylesat System.Number.ParseInt32(String s, NumberStyles
style, NumberFormatInfo info)style, NumberFormatInfo info)
at System.Int32.Parse(String s)at System.Int32.Parse(String s)
at ExceptionsTest.CauseFormatException() inat ExceptionsTest.CauseFormatException() in
c:consoleapplication1exceptionstest.cs:line 8c:consoleapplication1exceptionstest.cs:line 8
at ExceptionsTest.Main(String[] args) inat ExceptionsTest.Main(String[] args) in
c:consoleapplication1exceptionstest.cs:line 15c:consoleapplication1exceptionstest.cs:line 15
11
Exception Properties (2)Exception Properties (2)
 File names and line numbers are accessible only if theFile names and line numbers are accessible only if the
compilation was incompilation was in DebugDebug modemode
 When compiled inWhen compiled in ReleaseRelease mode, the information inmode, the information in
the propertythe property StackTraceStackTrace is quite different:is quite different:
Exception caught: Input string was not in a correctException caught: Input string was not in a correct
format.format.
at System.Number.ParseInt32(String s, NumberStylesat System.Number.ParseInt32(String s, NumberStyles
style, NumberFormatInfo info)style, NumberFormatInfo info)
at ExceptionsTest.Main(String[] args)at ExceptionsTest.Main(String[] args)
12
Exception PropertiesException Properties
Live DemoLive Demo
The Hierarchy ofThe Hierarchy of
ExceptionsExceptions
 Exceptions in .NET Framework are organizedExceptions in .NET Framework are organized
in a hierarchyin a hierarchy
Exception HierarchyException Hierarchy
15
Types of ExceptionsTypes of Exceptions
 All .NET exceptions inherit fromAll .NET exceptions inherit from System.ExceptionSystem.Exception
 The system exceptions inherit fromThe system exceptions inherit from
System.SystemExceptionSystem.SystemException, e.g., e.g.
 System.ArgumentExceptionSystem.ArgumentException
 System.NullReferenceExceptionSystem.NullReferenceException
 System.OutOfMemoryExceptionSystem.OutOfMemoryException
 System.StackOverflowExceptionSystem.StackOverflowException
 User-defined exceptions should inherit fromUser-defined exceptions should inherit from
System.ApplicationExceptionSystem.ApplicationException
16
Handling ExceptionsHandling Exceptions
 When catching an exception of a particular class, allWhen catching an exception of a particular class, all
its inheritors (child exceptions) are caught tooits inheritors (child exceptions) are caught too
 Example:Example:
HandlesHandles ArithmeticExceptionArithmeticException andand its successorsits successors
DivideByZeroExceptionDivideByZeroException andand OverflowExceptionOverflowException
trytry
{{
// Do some works that can raise an exception// Do some works that can raise an exception
}}
catch (System.ArithmeticException)catch (System.ArithmeticException)
{{
// Handle the caught arithmetic exception// Handle the caught arithmetic exception
}}
17
Find the Mistake!Find the Mistake!
static void Main(string[] args)static void Main(string[] args)
{{
string s = Console.ReadLine();string s = Console.ReadLine();
trytry
{{
Int32.Parse(s);Int32.Parse(s);
}}
catch (Exception)catch (Exception)
{{
Console.WriteLine("Can not parse the number!");Console.WriteLine("Can not parse the number!");
}}
catch (FormatException)catch (FormatException)
{{
Console.WriteLine("Invalid integer number!");Console.WriteLine("Invalid integer number!");
}}
catch (OverflowException)catch (OverflowException)
{{
Console.WriteLine(Console.WriteLine(
"The number is too big to fit in Int32!");"The number is too big to fit in Int32!");
}}
}}
This should be lastThis should be last
Unreachable codeUnreachable code
Unreachable codeUnreachable code
18
Handling All ExceptionsHandling All Exceptions
 All exceptions thrown by .NET managed codeAll exceptions thrown by .NET managed code
inherit theinherit the System.ExceptionSystem.Exception exceptionexception
 Unmanaged code can throw other exceptionsUnmanaged code can throw other exceptions
 For handling all exceptions (even unmanaged)For handling all exceptions (even unmanaged)
use the construction:use the construction:
trytry
{{
// Do some works that can raise any exception// Do some works that can raise any exception
}}
catchcatch
{{
// Handle the caught exception// Handle the caught exception
}}
19
Throwing ExceptionsThrowing Exceptions
Throwing ExceptionsThrowing Exceptions
 Exceptions are thrown (raised) byExceptions are thrown (raised) by throwthrow
keyword in C#keyword in C#
Used to notify the calling code in case ofUsed to notify the calling code in case of
error or unusual situationerror or unusual situation
 When an exception is thrown:When an exception is thrown:
The program execution stopsThe program execution stops
The exception travels over the stack until aThe exception travels over the stack until a
suitablesuitable catchcatch block is reached to handle itblock is reached to handle it
 Unhandled exceptions display error messageUnhandled exceptions display error message
21
How Exceptions Work?How Exceptions Work?
22
Main()Main()
Method 1Method 1
Method 2Method 2
Method NMethod N
2. Method call2. Method call
3. Method call3. Method call
4. Method call4. Method call……
Main()Main()
Method 1Method 1
Method 2Method 2
Method NMethod N
8. Find handler8. Find handler
7. Find handler7. Find handler
6. Find handler6. Find handler……
5. Throw an exception5. Throw an exception
.NET.NET
CLRCLR
1. Execute the
1. Execute theprogram
program
9. Find handler
9. Find handler
10. Display error message
10. Display error message
UsingUsing throwthrow KeywordKeyword
 Throwing an exception with error message:Throwing an exception with error message:
 Exceptions can take message and cause:Exceptions can take message and cause:
 NoteNote:: if the original exception is not passed theif the original exception is not passed the
initial cause of the exception is lostinitial cause of the exception is lost
throw new ArgumentException("Invalid amount!");throw new ArgumentException("Invalid amount!");
trytry
{{
Int32.Parse(str);Int32.Parse(str);
}}
catch (FormatException fe)catch (FormatException fe)
{{
throw new ArgumentException("Invalid number", fe);throw new ArgumentException("Invalid number", fe);
}}
23
Re-Throwing ExceptionsRe-Throwing Exceptions
 Caught exceptions can be re-thrown again:Caught exceptions can be re-thrown again:
trytry
{{
Int32.Parse(str);Int32.Parse(str);
}}
catch (FormatException fe)catch (FormatException fe)
{{
Console.WriteLine("Parse failed!");Console.WriteLine("Parse failed!");
throw fe; // Re-throw the caught exceptionthrow fe; // Re-throw the caught exception
}}
catch (FormatException)catch (FormatException)
{{
throw; // Re-throws tha last caught exceptionthrow; // Re-throws tha last caught exception
}}
24
Throwing Exceptions – ExampleThrowing Exceptions – Example
public static double Sqrt(double value)public static double Sqrt(double value)
{{
if (value < 0)if (value < 0)
throw new System.ArgumentOutOfRangeException(throw new System.ArgumentOutOfRangeException(
"Sqrt for negative numbers is undefined!");"Sqrt for negative numbers is undefined!");
return Math.Sqrt(value);return Math.Sqrt(value);
}}
static void Main()static void Main()
{{
trytry
{{
Sqrt(-1);Sqrt(-1);
}}
catch (ArgumentOutOfRangeException ex)catch (ArgumentOutOfRangeException ex)
{{
Console.Error.WriteLine("Error: " + ex.Message);Console.Error.WriteLine("Error: " + ex.Message);
throw;throw;
}}
}}
25
Throwing ExceptionsThrowing Exceptions
Live DemoLive Demo
Choosing Exception TypeChoosing Exception Type
27
 When an invalid parameter is passed to a method:When an invalid parameter is passed to a method:
 ArgumentExceptionArgumentException,, ArgumentNullExceptionArgumentNullException,,
ArgumentOutOfRangeExceptionArgumentOutOfRangeException
 When requested operation is not supportedWhen requested operation is not supported
 NotSupportedExceptionNotSupportedException
 When a method is still not implementedWhen a method is still not implemented
 NotImplementedExceptionNotImplementedException
 If no suitable standard exception class is availableIf no suitable standard exception class is available
 Create own exception class (inheritCreate own exception class (inherit ExceptionException))
UsingTry-Finally BlocksUsingTry-Finally Blocks
TheThe try-finallytry-finally ConstructionConstruction
 The construction:The construction:
 Ensures execution of given block in all casesEnsures execution of given block in all cases
 When exception is raised or not in theWhen exception is raised or not in the trytry blockblock
 Used for execution of cleaning-up code, e.g.Used for execution of cleaning-up code, e.g.
releasing resourcesreleasing resources
trytry
{{
// Do some work that can cause an exception// Do some work that can cause an exception
}}
finallyfinally
{{
// This block will always execute// This block will always execute
}}
29
try-finallytry-finally – Example– Example
static void TestTryFinally()static void TestTryFinally()
{{
Console.WriteLine("Code executed before try-finally.");Console.WriteLine("Code executed before try-finally.");
trytry
{{
string str = Console.ReadLine();string str = Console.ReadLine();
Int32.Parse(str);Int32.Parse(str);
Console.WriteLine("Parsing was successful.");Console.WriteLine("Parsing was successful.");
return; // Exit from the current methodreturn; // Exit from the current method
}}
catch (FormatException)catch (FormatException)
{{
Console.WriteLine("Parsing failed!");Console.WriteLine("Parsing failed!");
}}
finallyfinally
{{
Console.WriteLine("This cleanup code is always executed.");Console.WriteLine("This cleanup code is always executed.");
}}
Console.WriteLine("This code is after the try-finally block.");Console.WriteLine("This code is after the try-finally block.");
}}
30
Try-FinallyTry-Finally
Live DemoLive Demo
Exceptions: Best PracticesExceptions: Best Practices
Best PracticesBest Practices
 catchcatch blocks should begin with the exceptionsblocks should begin with the exceptions
lowest in the hierarchy and continue with thelowest in the hierarchy and continue with the
more general exceptionsmore general exceptions
Otherwise a compilation error will occurOtherwise a compilation error will occur
 EachEach catchcatch block should handle only theseblock should handle only these
exceptions which it expectsexceptions which it expects
Handling all exception disregarding their type isHandling all exception disregarding their type is
popular bad practice!popular bad practice!
 When raising an exception always pass to theWhen raising an exception always pass to the
constructor good explanation messageconstructor good explanation message
33
BestBest Practices (Practices (22))
 Exceptions can decrease the applicationExceptions can decrease the application
performanceperformance
Throw exceptions only in situations which areThrow exceptions only in situations which are
really exceptional and should be handledreally exceptional and should be handled
Do not throw exceptions in the normal programDo not throw exceptions in the normal program
control flow (e.g.: on invalid user input)control flow (e.g.: on invalid user input)
 Some exceptions can be thrown at any timeSome exceptions can be thrown at any time
with no way to predict them, e.g.:with no way to predict them, e.g.:
System.OutOfMemoryExceptionSystem.OutOfMemoryException
34
SummarySummary
 Exceptions provide flexible error handlingExceptions provide flexible error handling
mechanism in .NET Frameworkmechanism in .NET Framework
 Allow errors to be handled at multiple levelsAllow errors to be handled at multiple levels
 Each exception handler processes only errors ofEach exception handler processes only errors of
particular type (and its child types)particular type (and its child types)
 Other types of errors are processed by other handlersOther types of errors are processed by other handlers
 Unhandled exceptions cause error messagesUnhandled exceptions cause error messages
 Try-finally ensures that given code block is alwaysTry-finally ensures that given code block is always
executed (even when an exception is thrown)executed (even when an exception is thrown)
35
Exceptions HandlingExceptions Handling
Questions?Questions?
http://academy.telerik.com
ExercisesExercises
1.1. Write a program that reads an integer number andWrite a program that reads an integer number and
calculates and prints its square root. If the number iscalculates and prints its square root. If the number is
invalid or negative, print "Invalid number". In allinvalid or negative, print "Invalid number". In all
cases finally print "Good bye". Use try-catch-finally.cases finally print "Good bye". Use try-catch-finally.
2.2. Write a methodWrite a method ReadNumber(int start, intReadNumber(int start, int
end)end) that enters an integer number in given rangethat enters an integer number in given range
[start..end]. If invalid number or non-number text is[start..end]. If invalid number or non-number text is
entered, the method should throw an exception.entered, the method should throw an exception.
Based on this method write a program that entersBased on this method write a program that enters 1010
numbers:numbers:
aa11, a, a22, … a, … a1010, such that 1 < a, such that 1 < a11 < … < a< … < a1010 < 100< 100
37
Exercises (2)Exercises (2)
3.3. Write a program that enters file name along with itsWrite a program that enters file name along with its
full file path (e.g.full file path (e.g. C:WINDOWSwin.iniC:WINDOWSwin.ini), reads its), reads its
contents and prints it on the console. Find in MSDNcontents and prints it on the console. Find in MSDN
how to usehow to use System.IO.File.ReadAllText(…)System.IO.File.ReadAllText(…). Be. Be
sure to catch all possible exceptions and print user-sure to catch all possible exceptions and print user-
friendly error messages.friendly error messages.
4.4. Write a program that downloads a file from InternetWrite a program that downloads a file from Internet
(e.g.(e.g. http://www.devbg.org/img/Logo-BASD.jpghttp://www.devbg.org/img/Logo-BASD.jpg))
and stores it the current directory. Find in Googleand stores it the current directory. Find in Google
how to download files in C#. Be sure to catch allhow to download files in C#. Be sure to catch all
exceptions and to free any used resources in theexceptions and to free any used resources in the
finally block.finally block. 38

More Related Content

PPTX
Simulated Annealing
PPTX
Exception Handling in C#
PPT
C#.NET
PPTX
Virtual Private Networks (VPN) ppt
PPTX
Unit 2 Virtualization Part I.pptx
PPTX
LINQ in C#
PPTX
Operating system and its types
PPT
Fundamental of Computers
Simulated Annealing
Exception Handling in C#
C#.NET
Virtual Private Networks (VPN) ppt
Unit 2 Virtualization Part I.pptx
LINQ in C#
Operating system and its types
Fundamental of Computers

What's hot (20)

PPT
PPTX
I/O Streams
PPT
Threads And Synchronization in C#
PPTX
C# classes objects
PPTX
C# 101: Intro to Programming with C#
PPT
Final keyword in java
PPTX
Vectors in Java
PPT
Java: GUI
PPTX
ASP.NET - Life cycle of asp
PDF
Arrays in Java
PPTX
C# Delegates
PPTX
C# programming language
PPTX
Presentation on-exception-handling
PPTX
Exception handling
PPTX
Ado.Net Tutorial
PPTX
C# Arrays
PDF
JavaScript - Chapter 10 - Strings and Arrays
PPT
Cookies in servlet
I/O Streams
Threads And Synchronization in C#
C# classes objects
C# 101: Intro to Programming with C#
Final keyword in java
Vectors in Java
Java: GUI
ASP.NET - Life cycle of asp
Arrays in Java
C# Delegates
C# programming language
Presentation on-exception-handling
Exception handling
Ado.Net Tutorial
C# Arrays
JavaScript - Chapter 10 - Strings and Arrays
Cookies in servlet
Ad

Viewers also liked (14)

PPTX
Dementia dealing with sexually inappropriate behavior
PPTX
SydMobNet July 2014: Xamarin 3 & Xamarin Forms
PPTX
Xamarin day9 - Advance Xamarin Forms
PPTX
Modern .NET Apps - Telerik Webinar
PPTX
Xamarin Forms
PPTX
Xamarin Forms
PPTX
Xamarin forms Xaml + C#
PPT
Intro to Xamarin.Forms : A C# way to develop mobile app
PDF
Your First Xamarin.Forms App
PDF
DevDay Salerno - Introduzione a Xamarin
PDF
Introducción a Xamarin Forms con XAML
PPTX
Xamarin Forms
PDF
Introduction to Xamarin for Visual Studio 2017
PPTX
Xamarin Native vs Xamarin Forms
Dementia dealing with sexually inappropriate behavior
SydMobNet July 2014: Xamarin 3 & Xamarin Forms
Xamarin day9 - Advance Xamarin Forms
Modern .NET Apps - Telerik Webinar
Xamarin Forms
Xamarin Forms
Xamarin forms Xaml + C#
Intro to Xamarin.Forms : A C# way to develop mobile app
Your First Xamarin.Forms App
DevDay Salerno - Introduzione a Xamarin
Introducción a Xamarin Forms con XAML
Xamarin Forms
Introduction to Xamarin for Visual Studio 2017
Xamarin Native vs Xamarin Forms
Ad

Similar to C# Exceptions Handling (20)

PPTX
Exception Handlin g C#.pptx
PPTX
12. Exception Handling
PPTX
Exceptions overview
PPTX
Java exception handling
DOCX
Exception handlingpdf
PPTX
java exception.pptx
PPTX
12. Java Exceptions and error handling
PDF
ChakraCore: analysis of JavaScript-engine for Microsoft Edge
PDF
Skiron - Experiments in CPU Design in D
PPT
Java Exception Handling & IO-Unit-3 (1).ppt
PPT
Java Exception Handling & IO-Unit-3 (1).ppt
PPT
Comp102 lec 10
PPTX
Java-Exception Handling Presentation. 2024
PPTX
Exception Handling In Java Presentation. 2024
PPT
Exceptions
PPTX
OCA_1Z0-808_Module00_Introduction_Java.pptx
PDF
Exception Handling.pdf
PPTX
PVS-Studio and static code analysis technique
PPT
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
PPTX
Chapter i c#(console application and programming)
Exception Handlin g C#.pptx
12. Exception Handling
Exceptions overview
Java exception handling
Exception handlingpdf
java exception.pptx
12. Java Exceptions and error handling
ChakraCore: analysis of JavaScript-engine for Microsoft Edge
Skiron - Experiments in CPU Design in D
Java Exception Handling & IO-Unit-3 (1).ppt
Java Exception Handling & IO-Unit-3 (1).ppt
Comp102 lec 10
Java-Exception Handling Presentation. 2024
Exception Handling In Java Presentation. 2024
Exceptions
OCA_1Z0-808_Module00_Introduction_Java.pptx
Exception Handling.pdf
PVS-Studio and static code analysis technique
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
Chapter i c#(console application and programming)

Recently uploaded (20)

PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
DOCX
UPPER GASTRO INTESTINAL DISORDER.docx
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PPTX
COMPUTERS AS DATA ANALYSIS IN PRECLINICAL DEVELOPMENT.pptx
PPTX
How to Manage Starshipit in Odoo 18 - Odoo Slides
PPTX
Introduction and Scope of Bichemistry.pptx
PPTX
IMMUNIZATION PROGRAMME pptx
PPTX
Revamp in MTO Odoo 18 Inventory - Odoo Slides
PPTX
Onica Farming 24rsclub profitable farm business
PDF
Piense y hagase Rico - Napoleon Hill Ccesa007.pdf
PPTX
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
PPTX
Nursing Management of Patients with Disorders of Ear, Nose, and Throat (ENT) ...
PDF
From loneliness to social connection charting
PDF
Cell Biology Basics: Cell Theory, Structure, Types, and Organelles | BS Level...
PDF
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
PPTX
Cardiovascular Pharmacology for pharmacy students.pptx
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
Module 3: Health Systems Tutorial Slides S2 2025
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
Sunset Boulevard Student Revision Booklet
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
UPPER GASTRO INTESTINAL DISORDER.docx
Renaissance Architecture: A Journey from Faith to Humanism
COMPUTERS AS DATA ANALYSIS IN PRECLINICAL DEVELOPMENT.pptx
How to Manage Starshipit in Odoo 18 - Odoo Slides
Introduction and Scope of Bichemistry.pptx
IMMUNIZATION PROGRAMME pptx
Revamp in MTO Odoo 18 Inventory - Odoo Slides
Onica Farming 24rsclub profitable farm business
Piense y hagase Rico - Napoleon Hill Ccesa007.pdf
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
Nursing Management of Patients with Disorders of Ear, Nose, and Throat (ENT) ...
From loneliness to social connection charting
Cell Biology Basics: Cell Theory, Structure, Types, and Organelles | BS Level...
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
Cardiovascular Pharmacology for pharmacy students.pptx
Abdominal Access Techniques with Prof. Dr. R K Mishra
Module 3: Health Systems Tutorial Slides S2 2025
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
Sunset Boulevard Student Revision Booklet

C# Exceptions Handling

  • 1. Exceptions HandlingExceptions Handling Handling Errors during the Program ExecutionHandling Errors during the Program Execution Svetlin NakovSvetlin Nakov Telerik CorporationTelerik Corporation www.telerik.comwww.telerik.com
  • 2. Table of ContentsTable of Contents 1.1. What are Exceptions?What are Exceptions? 2.2. Handling ExceptionsHandling Exceptions 3.3. TheThe System.ExceptionSystem.Exception ClassClass 4.4. Types of Exceptions and theirTypes of Exceptions and their HierarchyHierarchy 5.5. RaisingRaising ((ThrowingThrowing)) ExceptionsExceptions 6.6. Best PracticesBest Practices 2
  • 3. What are Exceptions?What are Exceptions? The Paradigm of Exceptions in OOPThe Paradigm of Exceptions in OOP
  • 4. What are Exceptions?What are Exceptions?  The exceptions in .NET Framework are classicThe exceptions in .NET Framework are classic implementation of the OOP exception modelimplementation of the OOP exception model  Deliver powerful mechanism for centralizedDeliver powerful mechanism for centralized handling of errors and unusual eventshandling of errors and unusual events  Substitute procedure-oriented approach,Substitute procedure-oriented approach, in which each function returns error codein which each function returns error code  Simplify code construction and maintenanceSimplify code construction and maintenance  Allow the problematic situations to beAllow the problematic situations to be processed at multiple levelsprocessed at multiple levels 4
  • 5. Handling ExceptionsHandling Exceptions Catching and Processing ErrorsCatching and Processing Errors
  • 6. Handling ExceptionsHandling Exceptions  In C# the exceptions can be handled by theIn C# the exceptions can be handled by the try-catch-finallytry-catch-finally constructionconstruction  catchcatch blocks can be used multiple times toblocks can be used multiple times to process different exception typesprocess different exception types trytry {{ // Do some work that can raise an exception// Do some work that can raise an exception }} catch (SomeException)catch (SomeException) {{ // Handle the caught exception// Handle the caught exception }} 6
  • 7. Handling Exceptions – ExampleHandling Exceptions – Example static void Main()static void Main() {{ string s = Console.ReadLine();string s = Console.ReadLine(); trytry {{ Int32.Parse(s);Int32.Parse(s); Console.WriteLine(Console.WriteLine( "You entered valid Int32 number {0}.", s);"You entered valid Int32 number {0}.", s); }} catchcatch (FormatException)(FormatException) {{ Console.WriteLine("Invalid integer number!");Console.WriteLine("Invalid integer number!"); }} catchcatch (OverflowException)(OverflowException) {{ Console.WriteLine(Console.WriteLine( "The number is too big to fit in Int32!");"The number is too big to fit in Int32!"); }} }} 7
  • 9. TheThe System.ExceptionSystem.Exception ClassClass  Exceptions inExceptions in .NET.NET are objectsare objects  TheThe System.ExceptionSystem.Exception class is base for allclass is base for all exceptions in CLRexceptions in CLR  Contains information for the cause of the error orContains information for the cause of the error or the unusual situationthe unusual situation  MessageMessage –– text description of the exceptiontext description of the exception  StackTraceStackTrace –– the snapshot of the stack at thethe snapshot of the stack at the moment of exception throwingmoment of exception throwing  InnerExceptionInnerException –– exception caused the currentexception caused the current exceptionexception ((if anyif any)) 9
  • 10. Exception Properties – ExampleException Properties – Example class ExceptionsTestclass ExceptionsTest {{ public static void CauseFormatException()public static void CauseFormatException() {{ string s = "an invalid number";string s = "an invalid number"; Int32.Parse(s);Int32.Parse(s); }} static void Main()static void Main() {{ trytry {{ CauseFormatException();CauseFormatException(); }} catch (FormatException fe)catch (FormatException fe) {{ Console.Error.WriteLine("Exception caught: {0}n{1}",Console.Error.WriteLine("Exception caught: {0}n{1}", fe.Message, fe.StackTrace);fe.Message, fe.StackTrace); }} }} }} 10
  • 11. Exception PropertiesException Properties  TheThe MessageMessage property gives brief description of theproperty gives brief description of the problemproblem  TheThe StackTraceStackTrace property is extremely useful whenproperty is extremely useful when identifying the reason caused the exceptionidentifying the reason caused the exception Exception caught: Input string was not in a correctException caught: Input string was not in a correct format.format. at System.Number.ParseInt32(String s, NumberStylesat System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)style, NumberFormatInfo info) at System.Int32.Parse(String s)at System.Int32.Parse(String s) at ExceptionsTest.CauseFormatException() inat ExceptionsTest.CauseFormatException() in c:consoleapplication1exceptionstest.cs:line 8c:consoleapplication1exceptionstest.cs:line 8 at ExceptionsTest.Main(String[] args) inat ExceptionsTest.Main(String[] args) in c:consoleapplication1exceptionstest.cs:line 15c:consoleapplication1exceptionstest.cs:line 15 11
  • 12. Exception Properties (2)Exception Properties (2)  File names and line numbers are accessible only if theFile names and line numbers are accessible only if the compilation was incompilation was in DebugDebug modemode  When compiled inWhen compiled in ReleaseRelease mode, the information inmode, the information in the propertythe property StackTraceStackTrace is quite different:is quite different: Exception caught: Input string was not in a correctException caught: Input string was not in a correct format.format. at System.Number.ParseInt32(String s, NumberStylesat System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)style, NumberFormatInfo info) at ExceptionsTest.Main(String[] args)at ExceptionsTest.Main(String[] args) 12
  • 14. The Hierarchy ofThe Hierarchy of ExceptionsExceptions
  • 15.  Exceptions in .NET Framework are organizedExceptions in .NET Framework are organized in a hierarchyin a hierarchy Exception HierarchyException Hierarchy 15
  • 16. Types of ExceptionsTypes of Exceptions  All .NET exceptions inherit fromAll .NET exceptions inherit from System.ExceptionSystem.Exception  The system exceptions inherit fromThe system exceptions inherit from System.SystemExceptionSystem.SystemException, e.g., e.g.  System.ArgumentExceptionSystem.ArgumentException  System.NullReferenceExceptionSystem.NullReferenceException  System.OutOfMemoryExceptionSystem.OutOfMemoryException  System.StackOverflowExceptionSystem.StackOverflowException  User-defined exceptions should inherit fromUser-defined exceptions should inherit from System.ApplicationExceptionSystem.ApplicationException 16
  • 17. Handling ExceptionsHandling Exceptions  When catching an exception of a particular class, allWhen catching an exception of a particular class, all its inheritors (child exceptions) are caught tooits inheritors (child exceptions) are caught too  Example:Example: HandlesHandles ArithmeticExceptionArithmeticException andand its successorsits successors DivideByZeroExceptionDivideByZeroException andand OverflowExceptionOverflowException trytry {{ // Do some works that can raise an exception// Do some works that can raise an exception }} catch (System.ArithmeticException)catch (System.ArithmeticException) {{ // Handle the caught arithmetic exception// Handle the caught arithmetic exception }} 17
  • 18. Find the Mistake!Find the Mistake! static void Main(string[] args)static void Main(string[] args) {{ string s = Console.ReadLine();string s = Console.ReadLine(); trytry {{ Int32.Parse(s);Int32.Parse(s); }} catch (Exception)catch (Exception) {{ Console.WriteLine("Can not parse the number!");Console.WriteLine("Can not parse the number!"); }} catch (FormatException)catch (FormatException) {{ Console.WriteLine("Invalid integer number!");Console.WriteLine("Invalid integer number!"); }} catch (OverflowException)catch (OverflowException) {{ Console.WriteLine(Console.WriteLine( "The number is too big to fit in Int32!");"The number is too big to fit in Int32!"); }} }} This should be lastThis should be last Unreachable codeUnreachable code Unreachable codeUnreachable code 18
  • 19. Handling All ExceptionsHandling All Exceptions  All exceptions thrown by .NET managed codeAll exceptions thrown by .NET managed code inherit theinherit the System.ExceptionSystem.Exception exceptionexception  Unmanaged code can throw other exceptionsUnmanaged code can throw other exceptions  For handling all exceptions (even unmanaged)For handling all exceptions (even unmanaged) use the construction:use the construction: trytry {{ // Do some works that can raise any exception// Do some works that can raise any exception }} catchcatch {{ // Handle the caught exception// Handle the caught exception }} 19
  • 21. Throwing ExceptionsThrowing Exceptions  Exceptions are thrown (raised) byExceptions are thrown (raised) by throwthrow keyword in C#keyword in C# Used to notify the calling code in case ofUsed to notify the calling code in case of error or unusual situationerror or unusual situation  When an exception is thrown:When an exception is thrown: The program execution stopsThe program execution stops The exception travels over the stack until aThe exception travels over the stack until a suitablesuitable catchcatch block is reached to handle itblock is reached to handle it  Unhandled exceptions display error messageUnhandled exceptions display error message 21
  • 22. How Exceptions Work?How Exceptions Work? 22 Main()Main() Method 1Method 1 Method 2Method 2 Method NMethod N 2. Method call2. Method call 3. Method call3. Method call 4. Method call4. Method call…… Main()Main() Method 1Method 1 Method 2Method 2 Method NMethod N 8. Find handler8. Find handler 7. Find handler7. Find handler 6. Find handler6. Find handler…… 5. Throw an exception5. Throw an exception .NET.NET CLRCLR 1. Execute the 1. Execute theprogram program 9. Find handler 9. Find handler 10. Display error message 10. Display error message
  • 23. UsingUsing throwthrow KeywordKeyword  Throwing an exception with error message:Throwing an exception with error message:  Exceptions can take message and cause:Exceptions can take message and cause:  NoteNote:: if the original exception is not passed theif the original exception is not passed the initial cause of the exception is lostinitial cause of the exception is lost throw new ArgumentException("Invalid amount!");throw new ArgumentException("Invalid amount!"); trytry {{ Int32.Parse(str);Int32.Parse(str); }} catch (FormatException fe)catch (FormatException fe) {{ throw new ArgumentException("Invalid number", fe);throw new ArgumentException("Invalid number", fe); }} 23
  • 24. Re-Throwing ExceptionsRe-Throwing Exceptions  Caught exceptions can be re-thrown again:Caught exceptions can be re-thrown again: trytry {{ Int32.Parse(str);Int32.Parse(str); }} catch (FormatException fe)catch (FormatException fe) {{ Console.WriteLine("Parse failed!");Console.WriteLine("Parse failed!"); throw fe; // Re-throw the caught exceptionthrow fe; // Re-throw the caught exception }} catch (FormatException)catch (FormatException) {{ throw; // Re-throws tha last caught exceptionthrow; // Re-throws tha last caught exception }} 24
  • 25. Throwing Exceptions – ExampleThrowing Exceptions – Example public static double Sqrt(double value)public static double Sqrt(double value) {{ if (value < 0)if (value < 0) throw new System.ArgumentOutOfRangeException(throw new System.ArgumentOutOfRangeException( "Sqrt for negative numbers is undefined!");"Sqrt for negative numbers is undefined!"); return Math.Sqrt(value);return Math.Sqrt(value); }} static void Main()static void Main() {{ trytry {{ Sqrt(-1);Sqrt(-1); }} catch (ArgumentOutOfRangeException ex)catch (ArgumentOutOfRangeException ex) {{ Console.Error.WriteLine("Error: " + ex.Message);Console.Error.WriteLine("Error: " + ex.Message); throw;throw; }} }} 25
  • 27. Choosing Exception TypeChoosing Exception Type 27  When an invalid parameter is passed to a method:When an invalid parameter is passed to a method:  ArgumentExceptionArgumentException,, ArgumentNullExceptionArgumentNullException,, ArgumentOutOfRangeExceptionArgumentOutOfRangeException  When requested operation is not supportedWhen requested operation is not supported  NotSupportedExceptionNotSupportedException  When a method is still not implementedWhen a method is still not implemented  NotImplementedExceptionNotImplementedException  If no suitable standard exception class is availableIf no suitable standard exception class is available  Create own exception class (inheritCreate own exception class (inherit ExceptionException))
  • 29. TheThe try-finallytry-finally ConstructionConstruction  The construction:The construction:  Ensures execution of given block in all casesEnsures execution of given block in all cases  When exception is raised or not in theWhen exception is raised or not in the trytry blockblock  Used for execution of cleaning-up code, e.g.Used for execution of cleaning-up code, e.g. releasing resourcesreleasing resources trytry {{ // Do some work that can cause an exception// Do some work that can cause an exception }} finallyfinally {{ // This block will always execute// This block will always execute }} 29
  • 30. try-finallytry-finally – Example– Example static void TestTryFinally()static void TestTryFinally() {{ Console.WriteLine("Code executed before try-finally.");Console.WriteLine("Code executed before try-finally."); trytry {{ string str = Console.ReadLine();string str = Console.ReadLine(); Int32.Parse(str);Int32.Parse(str); Console.WriteLine("Parsing was successful.");Console.WriteLine("Parsing was successful."); return; // Exit from the current methodreturn; // Exit from the current method }} catch (FormatException)catch (FormatException) {{ Console.WriteLine("Parsing failed!");Console.WriteLine("Parsing failed!"); }} finallyfinally {{ Console.WriteLine("This cleanup code is always executed.");Console.WriteLine("This cleanup code is always executed."); }} Console.WriteLine("This code is after the try-finally block.");Console.WriteLine("This code is after the try-finally block."); }} 30
  • 33. Best PracticesBest Practices  catchcatch blocks should begin with the exceptionsblocks should begin with the exceptions lowest in the hierarchy and continue with thelowest in the hierarchy and continue with the more general exceptionsmore general exceptions Otherwise a compilation error will occurOtherwise a compilation error will occur  EachEach catchcatch block should handle only theseblock should handle only these exceptions which it expectsexceptions which it expects Handling all exception disregarding their type isHandling all exception disregarding their type is popular bad practice!popular bad practice!  When raising an exception always pass to theWhen raising an exception always pass to the constructor good explanation messageconstructor good explanation message 33
  • 34. BestBest Practices (Practices (22))  Exceptions can decrease the applicationExceptions can decrease the application performanceperformance Throw exceptions only in situations which areThrow exceptions only in situations which are really exceptional and should be handledreally exceptional and should be handled Do not throw exceptions in the normal programDo not throw exceptions in the normal program control flow (e.g.: on invalid user input)control flow (e.g.: on invalid user input)  Some exceptions can be thrown at any timeSome exceptions can be thrown at any time with no way to predict them, e.g.:with no way to predict them, e.g.: System.OutOfMemoryExceptionSystem.OutOfMemoryException 34
  • 35. SummarySummary  Exceptions provide flexible error handlingExceptions provide flexible error handling mechanism in .NET Frameworkmechanism in .NET Framework  Allow errors to be handled at multiple levelsAllow errors to be handled at multiple levels  Each exception handler processes only errors ofEach exception handler processes only errors of particular type (and its child types)particular type (and its child types)  Other types of errors are processed by other handlersOther types of errors are processed by other handlers  Unhandled exceptions cause error messagesUnhandled exceptions cause error messages  Try-finally ensures that given code block is alwaysTry-finally ensures that given code block is always executed (even when an exception is thrown)executed (even when an exception is thrown) 35
  • 37. ExercisesExercises 1.1. Write a program that reads an integer number andWrite a program that reads an integer number and calculates and prints its square root. If the number iscalculates and prints its square root. If the number is invalid or negative, print "Invalid number". In allinvalid or negative, print "Invalid number". In all cases finally print "Good bye". Use try-catch-finally.cases finally print "Good bye". Use try-catch-finally. 2.2. Write a methodWrite a method ReadNumber(int start, intReadNumber(int start, int end)end) that enters an integer number in given rangethat enters an integer number in given range [start..end]. If invalid number or non-number text is[start..end]. If invalid number or non-number text is entered, the method should throw an exception.entered, the method should throw an exception. Based on this method write a program that entersBased on this method write a program that enters 1010 numbers:numbers: aa11, a, a22, … a, … a1010, such that 1 < a, such that 1 < a11 < … < a< … < a1010 < 100< 100 37
  • 38. Exercises (2)Exercises (2) 3.3. Write a program that enters file name along with itsWrite a program that enters file name along with its full file path (e.g.full file path (e.g. C:WINDOWSwin.iniC:WINDOWSwin.ini), reads its), reads its contents and prints it on the console. Find in MSDNcontents and prints it on the console. Find in MSDN how to usehow to use System.IO.File.ReadAllText(…)System.IO.File.ReadAllText(…). Be. Be sure to catch all possible exceptions and print user-sure to catch all possible exceptions and print user- friendly error messages.friendly error messages. 4.4. Write a program that downloads a file from InternetWrite a program that downloads a file from Internet (e.g.(e.g. http://www.devbg.org/img/Logo-BASD.jpghttp://www.devbg.org/img/Logo-BASD.jpg)) and stores it the current directory. Find in Googleand stores it the current directory. Find in Google how to download files in C#. Be sure to catch allhow to download files in C#. Be sure to catch all exceptions and to free any used resources in theexceptions and to free any used resources in the finally block.finally block. 38