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

What's hot (20)

PDF
Object-oriented Programming-with C#
Doncho Minkov
 
PPT
C# basics
Dinesh kumar
 
PPT
C# Basics
Sunil OS
 
PPTX
Dot net assembly
Dr.Neeraj Kumar Pandey
 
PPTX
Presentation1
Anul Chaudhary
 
PPT
Java interfaces
Raja Sekhar
 
PPTX
Ado.Net Tutorial
prabhu rajendran
 
PPTX
Delegates and events in C#
Dr.Neeraj Kumar Pandey
 
PPTX
Namespaces in C#
yogita kachve
 
PPTX
C# language
Akanksha Shukla
 
PPTX
Java abstract class & abstract methods
Shubham Dwivedi
 
PPTX
L14 exception handling
teach4uin
 
PPSX
ADO.NET
Farzad Wadia
 
PPTX
Microsoft dot net framework
Ashish Verma
 
PPTX
Core java
Shivaraj R
 
PPTX
C# Delegates
Raghuveer Guthikonda
 
PPTX
C# classes objects
Dr.Neeraj Kumar Pandey
 
PPTX
Access specifiers(modifiers) in java
HrithikShinde
 
Object-oriented Programming-with C#
Doncho Minkov
 
C# basics
Dinesh kumar
 
C# Basics
Sunil OS
 
Dot net assembly
Dr.Neeraj Kumar Pandey
 
Presentation1
Anul Chaudhary
 
Java interfaces
Raja Sekhar
 
Ado.Net Tutorial
prabhu rajendran
 
Delegates and events in C#
Dr.Neeraj Kumar Pandey
 
Namespaces in C#
yogita kachve
 
C# language
Akanksha Shukla
 
Java abstract class & abstract methods
Shubham Dwivedi
 
L14 exception handling
teach4uin
 
ADO.NET
Farzad Wadia
 
Microsoft dot net framework
Ashish Verma
 
Core java
Shivaraj R
 
C# Delegates
Raghuveer Guthikonda
 
C# classes objects
Dr.Neeraj Kumar Pandey
 
Access specifiers(modifiers) in java
HrithikShinde
 

Viewers also liked (14)

PPTX
Dementia dealing with sexually inappropriate behavior
Helen Medeiros Taylor, R.N., J.D.
 
PPTX
SydMobNet July 2014: Xamarin 3 & Xamarin Forms
Alec Tucker
 
PPTX
Xamarin day9 - Advance Xamarin Forms
Subodh Pushpak
 
PPTX
Modern .NET Apps - Telerik Webinar
Sam Basu
 
PPTX
Xamarin Forms
Peter Major
 
PPTX
Xamarin Forms
Sam Nasr, MCSA, MVP
 
PPTX
Xamarin forms Xaml + C#
Andrés Londoño
 
PPT
Intro to Xamarin.Forms : A C# way to develop mobile app
Mindfire Solutions
 
PDF
Your First Xamarin.Forms App
Craig Dunn
 
PDF
DevDay Salerno - Introduzione a Xamarin
Antonio Liccardi
 
PDF
Introducción a Xamarin Forms con XAML
Sorey García
 
PPTX
Xamarin Forms
Fabio Cozzolino
 
PDF
Introduction to Xamarin for Visual Studio 2017
Xamarin
 
PPTX
Xamarin Native vs Xamarin Forms
Tomohiro Suzuki
 
Dementia dealing with sexually inappropriate behavior
Helen Medeiros Taylor, R.N., J.D.
 
SydMobNet July 2014: Xamarin 3 & Xamarin Forms
Alec Tucker
 
Xamarin day9 - Advance Xamarin Forms
Subodh Pushpak
 
Modern .NET Apps - Telerik Webinar
Sam Basu
 
Xamarin Forms
Peter Major
 
Xamarin Forms
Sam Nasr, MCSA, MVP
 
Xamarin forms Xaml + C#
Andrés Londoño
 
Intro to Xamarin.Forms : A C# way to develop mobile app
Mindfire Solutions
 
Your First Xamarin.Forms App
Craig Dunn
 
DevDay Salerno - Introduzione a Xamarin
Antonio Liccardi
 
Introducción a Xamarin Forms con XAML
Sorey García
 
Xamarin Forms
Fabio Cozzolino
 
Introduction to Xamarin for Visual Studio 2017
Xamarin
 
Xamarin Native vs Xamarin Forms
Tomohiro Suzuki
 
Ad

Similar to C# Exceptions Handling (20)

PPTX
Exception Handlin g C#.pptx
R S Anu Prabha
 
PPTX
12. Exception Handling
Intro C# Book
 
PPTX
Exceptions overview
Bharath K
 
PPTX
Java exception handling
BHUVIJAYAVELU
 
DOCX
Exception handlingpdf
gandra jeeshitha
 
PPTX
java exception.pptx
SukhpreetSingh519414
 
PPTX
12. Java Exceptions and error handling
Intro C# Book
 
PDF
ChakraCore: analysis of JavaScript-engine for Microsoft Edge
PVS-Studio
 
PDF
Skiron - Experiments in CPU Design in D
Mithun Hunsur
 
PPT
Java Exception Handling & IO-Unit-3 (1).ppt
SahilKumar542
 
PPT
Java Exception Handling & IO-Unit-3 (1).ppt
SahilKumar542
 
PPT
Comp102 lec 10
Fraz Bakhsh
 
PPTX
Java-Exception Handling Presentation. 2024
nehakumari0xf
 
PPTX
Exception Handling In Java Presentation. 2024
kashyapneha2809
 
PPT
Exceptions
motthu18
 
PDF
Exception Handling.pdf
lsdfjldskjf
 
PPTX
PVS-Studio and static code analysis technique
Andrey Karpov
 
PPT
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
ssuserf45a65
 
PPTX
Chapter i c#(console application and programming)
Chhom Karath
 
DOCX
Exception handling in java
gopalrajput11
 
Exception Handlin g C#.pptx
R S Anu Prabha
 
12. Exception Handling
Intro C# Book
 
Exceptions overview
Bharath K
 
Java exception handling
BHUVIJAYAVELU
 
Exception handlingpdf
gandra jeeshitha
 
java exception.pptx
SukhpreetSingh519414
 
12. Java Exceptions and error handling
Intro C# Book
 
ChakraCore: analysis of JavaScript-engine for Microsoft Edge
PVS-Studio
 
Skiron - Experiments in CPU Design in D
Mithun Hunsur
 
Java Exception Handling & IO-Unit-3 (1).ppt
SahilKumar542
 
Java Exception Handling & IO-Unit-3 (1).ppt
SahilKumar542
 
Comp102 lec 10
Fraz Bakhsh
 
Java-Exception Handling Presentation. 2024
nehakumari0xf
 
Exception Handling In Java Presentation. 2024
kashyapneha2809
 
Exceptions
motthu18
 
Exception Handling.pdf
lsdfjldskjf
 
PVS-Studio and static code analysis technique
Andrey Karpov
 
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
ssuserf45a65
 
Chapter i c#(console application and programming)
Chhom Karath
 
Exception handling in java
gopalrajput11
 
Ad

Recently uploaded (20)

PDF
People & Earth's Ecosystem -Lesson 2: People & Population
marvinnbustamante1
 
PDF
The dynastic history of the Chahmana.pdf
PrachiSontakke5
 
PDF
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - GLOBAL SUCCESS - CẢ NĂM - NĂM 2024 (VOCABULARY, ...
Nguyen Thanh Tu Collection
 
PPTX
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
PDF
CEREBRAL PALSY: NURSING MANAGEMENT .pdf
PRADEEP ABOTHU
 
PDF
community health nursing question paper 2.pdf
Prince kumar
 
PPTX
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
PPTX
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
PPTX
2025 Winter SWAYAM NPTEL & A Student.pptx
Utsav Yagnik
 
PDF
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
PPTX
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
PDF
The Different Types of Non-Experimental Research
Thelma Villaflores
 
PDF
Dimensions of Societal Planning in Commonism
StefanMz
 
PPTX
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
PDF
LAW OF CONTRACT (5 YEAR LLB & UNITARY LLB )- MODULE - 1.& 2 - LEARN THROUGH P...
APARNA T SHAIL KUMAR
 
PPSX
HEALTH ASSESSMENT (Community Health Nursing) - GNM 1st Year
Priyanshu Anand
 
PDF
The-Ever-Evolving-World-of-Science (1).pdf/7TH CLASS CURIOSITY /1ST CHAPTER/B...
Sandeep Swamy
 
PDF
Isharyanti-2025-Cross Language Communication in Indonesian Language
Neny Isharyanti
 
PDF
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
PPTX
STAFF DEVELOPMENT AND WELFARE: MANAGEMENT
PRADEEP ABOTHU
 
People & Earth's Ecosystem -Lesson 2: People & Population
marvinnbustamante1
 
The dynastic history of the Chahmana.pdf
PrachiSontakke5
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - GLOBAL SUCCESS - CẢ NĂM - NĂM 2024 (VOCABULARY, ...
Nguyen Thanh Tu Collection
 
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
CEREBRAL PALSY: NURSING MANAGEMENT .pdf
PRADEEP ABOTHU
 
community health nursing question paper 2.pdf
Prince kumar
 
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
2025 Winter SWAYAM NPTEL & A Student.pptx
Utsav Yagnik
 
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
The Different Types of Non-Experimental Research
Thelma Villaflores
 
Dimensions of Societal Planning in Commonism
StefanMz
 
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
LAW OF CONTRACT (5 YEAR LLB & UNITARY LLB )- MODULE - 1.& 2 - LEARN THROUGH P...
APARNA T SHAIL KUMAR
 
HEALTH ASSESSMENT (Community Health Nursing) - GNM 1st Year
Priyanshu Anand
 
The-Ever-Evolving-World-of-Science (1).pdf/7TH CLASS CURIOSITY /1ST CHAPTER/B...
Sandeep Swamy
 
Isharyanti-2025-Cross Language Communication in Indonesian Language
Neny Isharyanti
 
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
STAFF DEVELOPMENT AND WELFARE: MANAGEMENT
PRADEEP ABOTHU
 

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