SlideShare uma empresa Scribd logo
1 de 38
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

Mais conteúdo relacionado

Mais procurados (20)

Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Exception handling
Exception handlingException handling
Exception handling
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Common language runtime clr
Common language runtime clrCommon language runtime clr
Common language runtime clr
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
JAVA AWT
JAVA AWTJAVA AWT
JAVA AWT
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
C# Arrays
C# ArraysC# Arrays
C# Arrays
 
Delegates and events in C#
Delegates and events in C#Delegates and events in C#
Delegates and events in C#
 
Delegates in C#
Delegates in C#Delegates in C#
Delegates in C#
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in Java
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception Handling In Java
Exception Handling In JavaException Handling In Java
Exception Handling In Java
 
Introduction To C#
Introduction To C#Introduction To C#
Introduction To C#
 
Java awt
Java awtJava awt
Java awt
 
Abstract class in java
Abstract class in javaAbstract class in java
Abstract class in java
 
Java I/O
Java I/OJava I/O
Java I/O
 
Java Presentation For Syntax
Java Presentation For SyntaxJava Presentation For Syntax
Java Presentation For Syntax
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 

Destaque

SydMobNet July 2014: Xamarin 3 & Xamarin Forms
SydMobNet July 2014: Xamarin 3 & Xamarin FormsSydMobNet July 2014: Xamarin 3 & Xamarin Forms
SydMobNet July 2014: Xamarin 3 & Xamarin FormsAlec Tucker
 
Xamarin day9 - Advance Xamarin Forms
Xamarin day9 - Advance Xamarin FormsXamarin day9 - Advance Xamarin Forms
Xamarin day9 - Advance Xamarin FormsSubodh Pushpak
 
Modern .NET Apps - Telerik Webinar
Modern .NET Apps - Telerik WebinarModern .NET Apps - Telerik Webinar
Modern .NET Apps - Telerik WebinarSam Basu
 
Intro to Xamarin.Forms : A C# way to develop mobile app
Intro to Xamarin.Forms : A C# way to develop mobile appIntro to Xamarin.Forms : A C# way to develop mobile app
Intro to Xamarin.Forms : A C# way to develop mobile appMindfire Solutions
 
Your First Xamarin.Forms App
Your First Xamarin.Forms AppYour First Xamarin.Forms App
Your First Xamarin.Forms AppCraig Dunn
 
DevDay Salerno - Introduzione a Xamarin
DevDay Salerno - Introduzione a XamarinDevDay Salerno - Introduzione a Xamarin
DevDay Salerno - Introduzione a XamarinAntonio Liccardi
 
Introducción a Xamarin Forms con XAML
Introducción a Xamarin Forms con XAMLIntroducción a Xamarin Forms con XAML
Introducción a Xamarin Forms con XAMLSorey García
 
Introduction to Xamarin for Visual Studio 2017
Introduction to Xamarin for Visual Studio 2017Introduction to Xamarin for Visual Studio 2017
Introduction to Xamarin for Visual Studio 2017Xamarin
 
Xamarin Native vs Xamarin Forms
Xamarin Native vs Xamarin FormsXamarin Native vs Xamarin Forms
Xamarin Native vs Xamarin FormsTomohiro Suzuki
 

Destaque (14)

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

Semelhante a C# Exceptions Handling

Exception Handlin g C#.pptx
Exception Handlin g C#.pptxException Handlin g C#.pptx
Exception Handlin g C#.pptxR S Anu Prabha
 
12. Exception Handling
12. Exception Handling 12. Exception Handling
12. Exception Handling Intro C# Book
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overviewBharath K
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handlingIntro C# Book
 
ChakraCore: analysis of JavaScript-engine for Microsoft Edge
ChakraCore: analysis of JavaScript-engine for Microsoft EdgeChakraCore: analysis of JavaScript-engine for Microsoft Edge
ChakraCore: analysis of JavaScript-engine for Microsoft EdgePVS-Studio
 
Skiron - Experiments in CPU Design in D
Skiron - Experiments in CPU Design in DSkiron - Experiments in CPU Design in D
Skiron - Experiments in CPU Design in DMithun Hunsur
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024nehakumari0xf
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024kashyapneha2809
 
Exceptions
ExceptionsExceptions
Exceptionsmotthu18
 
Exception Handling.pdf
Exception Handling.pdfException Handling.pdf
Exception Handling.pdflsdfjldskjf
 
PVS-Studio and static code analysis technique
PVS-Studio and static code analysis techniquePVS-Studio and static code analysis technique
PVS-Studio and static code analysis techniqueAndrey Karpov
 
Chapter i c#(console application and programming)
Chapter i c#(console application and programming)Chapter i c#(console application and programming)
Chapter i c#(console application and programming)Chhom Karath
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javagopalrajput11
 
"Why is there no artificial intelligence yet?" Or, analysis of CNTK tool kit ...
"Why is there no artificial intelligence yet?" Or, analysis of CNTK tool kit ..."Why is there no artificial intelligence yet?" Or, analysis of CNTK tool kit ...
"Why is there no artificial intelligence yet?" Or, analysis of CNTK tool kit ...PVS-Studio
 
Applying Compiler Techniques to Iterate At Blazing Speed
Applying Compiler Techniques to Iterate At Blazing SpeedApplying Compiler Techniques to Iterate At Blazing Speed
Applying Compiler Techniques to Iterate At Blazing SpeedPascal-Louis Perez
 
A exception ekon16
A exception ekon16A exception ekon16
A exception ekon16Max Kleiner
 
JP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.pptJP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.pptJAYAPRIYAR7
 

Semelhante a C# Exceptions Handling (20)

Exception Handlin g C#.pptx
Exception Handlin g C#.pptxException Handlin g C#.pptx
Exception Handlin g C#.pptx
 
12. Exception Handling
12. Exception Handling 12. Exception Handling
12. Exception Handling
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
 
Exception handlingpdf
Exception handlingpdfException handlingpdf
Exception handlingpdf
 
java exception.pptx
java exception.pptxjava exception.pptx
java exception.pptx
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handling
 
ChakraCore: analysis of JavaScript-engine for Microsoft Edge
ChakraCore: analysis of JavaScript-engine for Microsoft EdgeChakraCore: analysis of JavaScript-engine for Microsoft Edge
ChakraCore: analysis of JavaScript-engine for Microsoft Edge
 
Skiron - Experiments in CPU Design in D
Skiron - Experiments in CPU Design in DSkiron - Experiments in CPU Design in D
Skiron - Experiments in CPU Design in D
 
Comp102 lec 10
Comp102   lec 10Comp102   lec 10
Comp102 lec 10
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
 
Exceptions
ExceptionsExceptions
Exceptions
 
Exception Handling.pdf
Exception Handling.pdfException Handling.pdf
Exception Handling.pdf
 
PVS-Studio and static code analysis technique
PVS-Studio and static code analysis techniquePVS-Studio and static code analysis technique
PVS-Studio and static code analysis technique
 
Chapter i c#(console application and programming)
Chapter i c#(console application and programming)Chapter i c#(console application and programming)
Chapter i c#(console application and programming)
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
"Why is there no artificial intelligence yet?" Or, analysis of CNTK tool kit ...
"Why is there no artificial intelligence yet?" Or, analysis of CNTK tool kit ..."Why is there no artificial intelligence yet?" Or, analysis of CNTK tool kit ...
"Why is there no artificial intelligence yet?" Or, analysis of CNTK tool kit ...
 
Applying Compiler Techniques to Iterate At Blazing Speed
Applying Compiler Techniques to Iterate At Blazing SpeedApplying Compiler Techniques to Iterate At Blazing Speed
Applying Compiler Techniques to Iterate At Blazing Speed
 
A exception ekon16
A exception ekon16A exception ekon16
A exception ekon16
 
JP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.pptJP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.ppt
 

Último

Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...DhatriParmar
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfVanessa Camilleri
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmStan Meyer
 
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQ-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQuiz Club NITW
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfPrerana Jadhav
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxkarenfajardo43
 
ICS 2208 Lecture Slide Notes for Topic 6
ICS 2208 Lecture Slide Notes for Topic 6ICS 2208 Lecture Slide Notes for Topic 6
ICS 2208 Lecture Slide Notes for Topic 6Vanessa Camilleri
 
4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptxmary850239
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfPatidar M
 
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...DhatriParmar
 
How to Manage Buy 3 Get 1 Free in Odoo 17
How to Manage Buy 3 Get 1 Free in Odoo 17How to Manage Buy 3 Get 1 Free in Odoo 17
How to Manage Buy 3 Get 1 Free in Odoo 17Celine George
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operationalssuser3e220a
 
CLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptxCLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptxAnupam32727
 
4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptxmary850239
 
Using Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea DevelopmentUsing Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea Developmentchesterberbo7
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research DiscourseAnita GoswamiGiri
 
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
Unraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptxUnraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptx
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptxDhatriParmar
 
Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1GloryAnnCastre1
 
Sulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their usesSulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their usesVijayaLaxmi84
 

Último (20)

Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdf
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and Film
 
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQ-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdf
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
 
ICS 2208 Lecture Slide Notes for Topic 6
ICS 2208 Lecture Slide Notes for Topic 6ICS 2208 Lecture Slide Notes for Topic 6
ICS 2208 Lecture Slide Notes for Topic 6
 
4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdf
 
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
 
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptxINCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
 
How to Manage Buy 3 Get 1 Free in Odoo 17
How to Manage Buy 3 Get 1 Free in Odoo 17How to Manage Buy 3 Get 1 Free in Odoo 17
How to Manage Buy 3 Get 1 Free in Odoo 17
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operational
 
CLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptxCLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptx
 
4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx
 
Using Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea DevelopmentUsing Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea Development
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research Discourse
 
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
Unraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptxUnraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptx
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
 
Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1
 
Sulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their usesSulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their uses
 

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