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

More Related Content

What's hot

Checking Clang 11 with PVS-Studio
Checking Clang 11 with PVS-StudioChecking Clang 11 with PVS-Studio
Checking Clang 11 with PVS-StudioAndrey Karpov
 
PVS-Studio. Static code analyzer. Windows/Linux, C/C++/C#. 2017
PVS-Studio. Static code analyzer. Windows/Linux, C/C++/C#. 2017PVS-Studio. Static code analyzer. Windows/Linux, C/C++/C#. 2017
PVS-Studio. Static code analyzer. Windows/Linux, C/C++/C#. 2017Andrey Karpov
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handlingteach4uin
 
Handling Exceptions In C &amp; C++[Part A]
Handling Exceptions In C &amp; C++[Part A]Handling Exceptions In C &amp; C++[Part A]
Handling Exceptions In C &amp; C++[Part A]ppd1961
 
PVS-Studio is ready to improve the code of Tizen operating system
PVS-Studio is ready to improve the code of Tizen operating systemPVS-Studio is ready to improve the code of Tizen operating system
PVS-Studio is ready to improve the code of Tizen operating systemAndrey Karpov
 
Checking 7-Zip with PVS-Studio analyzer
Checking 7-Zip with PVS-Studio analyzerChecking 7-Zip with PVS-Studio analyzer
Checking 7-Zip with PVS-Studio analyzerPVS-Studio
 
PVS-Studio is there to help CERN: analysis of Geant4 project
PVS-Studio is there to help CERN: analysis of Geant4 projectPVS-Studio is there to help CERN: analysis of Geant4 project
PVS-Studio is there to help CERN: analysis of Geant4 projectPVS-Studio
 
Exceptions &amp; Its Handling
Exceptions &amp; Its HandlingExceptions &amp; Its Handling
Exceptions &amp; Its HandlingBharat17485
 
Exceptions
ExceptionsExceptions
Exceptionsmotthu18
 
An introduction to JVM performance
An introduction to JVM performanceAn introduction to JVM performance
An introduction to JVM performanceRafael Winterhalter
 
Java - Exception Handling Concepts
Java - Exception Handling ConceptsJava - Exception Handling Concepts
Java - Exception Handling ConceptsVicter Paul
 
14 exception handling
14 exception handling14 exception handling
14 exception handlingjigeno
 
C++ Code as Seen by a Hypercritical Reviewer
C++ Code as Seen by a Hypercritical ReviewerC++ Code as Seen by a Hypercritical Reviewer
C++ Code as Seen by a Hypercritical ReviewerAndrey Karpov
 
Headache from using mathematical software
Headache from using mathematical softwareHeadache from using mathematical software
Headache from using mathematical softwarePVS-Studio
 
Software Vulnerabilities in C and C++ (CppCon 2018)
Software Vulnerabilities in C and C++ (CppCon 2018)Software Vulnerabilities in C and C++ (CppCon 2018)
Software Vulnerabilities in C and C++ (CppCon 2018)Patricia Aas
 

What's hot (20)

Checking Clang 11 with PVS-Studio
Checking Clang 11 with PVS-StudioChecking Clang 11 with PVS-Studio
Checking Clang 11 with PVS-Studio
 
PVS-Studio. Static code analyzer. Windows/Linux, C/C++/C#. 2017
PVS-Studio. Static code analyzer. Windows/Linux, C/C++/C#. 2017PVS-Studio. Static code analyzer. Windows/Linux, C/C++/C#. 2017
PVS-Studio. Static code analyzer. Windows/Linux, C/C++/C#. 2017
 
Built in exceptions
Built in exceptions Built in exceptions
Built in exceptions
 
Exception handling
Exception handlingException handling
Exception handling
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handling
 
Handling Exceptions In C &amp; C++[Part A]
Handling Exceptions In C &amp; C++[Part A]Handling Exceptions In C &amp; C++[Part A]
Handling Exceptions In C &amp; C++[Part A]
 
PVS-Studio is ready to improve the code of Tizen operating system
PVS-Studio is ready to improve the code of Tizen operating systemPVS-Studio is ready to improve the code of Tizen operating system
PVS-Studio is ready to improve the code of Tizen operating system
 
Listen afup 2010
Listen afup 2010Listen afup 2010
Listen afup 2010
 
Java exception
Java exception Java exception
Java exception
 
Checking 7-Zip with PVS-Studio analyzer
Checking 7-Zip with PVS-Studio analyzerChecking 7-Zip with PVS-Studio analyzer
Checking 7-Zip with PVS-Studio analyzer
 
PVS-Studio is there to help CERN: analysis of Geant4 project
PVS-Studio is there to help CERN: analysis of Geant4 projectPVS-Studio is there to help CERN: analysis of Geant4 project
PVS-Studio is there to help CERN: analysis of Geant4 project
 
Exceptions &amp; Its Handling
Exceptions &amp; Its HandlingExceptions &amp; Its Handling
Exceptions &amp; Its Handling
 
Exceptions
ExceptionsExceptions
Exceptions
 
An introduction to JVM performance
An introduction to JVM performanceAn introduction to JVM performance
An introduction to JVM performance
 
Java - Exception Handling Concepts
Java - Exception Handling ConceptsJava - Exception Handling Concepts
Java - Exception Handling Concepts
 
14 exception handling
14 exception handling14 exception handling
14 exception handling
 
C++ Code as Seen by a Hypercritical Reviewer
C++ Code as Seen by a Hypercritical ReviewerC++ Code as Seen by a Hypercritical Reviewer
C++ Code as Seen by a Hypercritical Reviewer
 
Headache from using mathematical software
Headache from using mathematical softwareHeadache from using mathematical software
Headache from using mathematical software
 
Software Vulnerabilities in C and C++ (CppCon 2018)
Software Vulnerabilities in C and C++ (CppCon 2018)Software Vulnerabilities in C and C++ (CppCon 2018)
Software Vulnerabilities in C and C++ (CppCon 2018)
 
Java review: try catch
Java review: try catchJava review: try catch
Java review: try catch
 

Viewers also liked

Basic VB problems
Basic VB problemsBasic VB problems
Basic VB problemsMukesh Das
 
Apostilajavacompleto 101230085521-phpapp02
Apostilajavacompleto 101230085521-phpapp02Apostilajavacompleto 101230085521-phpapp02
Apostilajavacompleto 101230085521-phpapp02cleitonDP
 
.NET history and careers
.NET history and careers.NET history and careers
.NET history and careersShiny Zhu
 
How to find a job
How to find a jobHow to find a job
How to find a jobShiny Zhu
 
Tutorial realidade aumentada - Sociesc 2011
Tutorial realidade aumentada - Sociesc 2011Tutorial realidade aumentada - Sociesc 2011
Tutorial realidade aumentada - Sociesc 2011Lorival Smolski Chapuis
 
C++ Programming Course
C++ Programming CourseC++ Programming Course
C++ Programming CourseDennis Chang
 
from java to c
from java to cfrom java to c
from java to cVõ Hòa
 
Novidades do Visual Basic .NET 10
Novidades do Visual Basic .NET 10Novidades do Visual Basic .NET 10
Novidades do Visual Basic .NET 10Comunidade NetPonto
 
Uso de uma rede neural artificial para previsão do volume de lodo gerado em e...
Uso de uma rede neural artificial para previsão do volume de lodo gerado em e...Uso de uma rede neural artificial para previsão do volume de lodo gerado em e...
Uso de uma rede neural artificial para previsão do volume de lodo gerado em e...Lorival Smolski Chapuis
 
Short notes of oop with java
Short notes of oop with javaShort notes of oop with java
Short notes of oop with javaMohamed Fathy
 
Basic concepts of object oriented programming
Basic concepts of object oriented programmingBasic concepts of object oriented programming
Basic concepts of object oriented programmingSachin Sharma
 
Object oriented programming (oop) cs304 power point slides lecture 01
Object oriented programming (oop)   cs304 power point slides lecture 01Object oriented programming (oop)   cs304 power point slides lecture 01
Object oriented programming (oop) cs304 power point slides lecture 01Adil Kakakhel
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Conceptsthinkphp
 

Viewers also liked (18)

Basic VB problems
Basic VB problemsBasic VB problems
Basic VB problems
 
Apostilajavacompleto 101230085521-phpapp02
Apostilajavacompleto 101230085521-phpapp02Apostilajavacompleto 101230085521-phpapp02
Apostilajavacompleto 101230085521-phpapp02
 
.NET history and careers
.NET history and careers.NET history and careers
.NET history and careers
 
How to find a job
How to find a jobHow to find a job
How to find a job
 
Tutorial realidade aumentada - Sociesc 2011
Tutorial realidade aumentada - Sociesc 2011Tutorial realidade aumentada - Sociesc 2011
Tutorial realidade aumentada - Sociesc 2011
 
C++ Programming Course
C++ Programming CourseC++ Programming Course
C++ Programming Course
 
from java to c
from java to cfrom java to c
from java to c
 
Novidades do Visual Basic .NET 10
Novidades do Visual Basic .NET 10Novidades do Visual Basic .NET 10
Novidades do Visual Basic .NET 10
 
Iadis Conference Flood Forecasting
Iadis Conference   Flood ForecastingIadis Conference   Flood Forecasting
Iadis Conference Flood Forecasting
 
Joinville Dojo 2010
Joinville Dojo   2010Joinville Dojo   2010
Joinville Dojo 2010
 
Uso de uma rede neural artificial para previsão do volume de lodo gerado em e...
Uso de uma rede neural artificial para previsão do volume de lodo gerado em e...Uso de uma rede neural artificial para previsão do volume de lodo gerado em e...
Uso de uma rede neural artificial para previsão do volume de lodo gerado em e...
 
Short notes of oop with java
Short notes of oop with javaShort notes of oop with java
Short notes of oop with java
 
01 introduction to oop and java
01 introduction to oop and java01 introduction to oop and java
01 introduction to oop and java
 
Php Oop
Php OopPhp Oop
Php Oop
 
Basic concepts of object oriented programming
Basic concepts of object oriented programmingBasic concepts of object oriented programming
Basic concepts of object oriented programming
 
Object oriented programming (oop) cs304 power point slides lecture 01
Object oriented programming (oop)   cs304 power point slides lecture 01Object oriented programming (oop)   cs304 power point slides lecture 01
Object oriented programming (oop) cs304 power point slides lecture 01
 
Object-oriented concepts
Object-oriented conceptsObject-oriented concepts
Object-oriented concepts
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Concepts
 

Similar to 12 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
 
Java exception handling
Java exception handlingJava exception handling
Java exception handlingBHUVIJAYAVELU
 
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
 
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
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024kashyapneha2809
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024nehakumari0xf
 
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
 
"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
 
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
 
.NET Foundation, Future of .NET and C#
.NET Foundation, Future of .NET and C#.NET Foundation, Future of .NET and C#
.NET Foundation, Future of .NET and C#Bertrand Le Roy
 
Python Exception Handling
Python Exception HandlingPython Exception Handling
Python Exception HandlingRTS Tech
 
Presentation slides: "How to get 100% code coverage"
Presentation slides: "How to get 100% code coverage" Presentation slides: "How to get 100% code coverage"
Presentation slides: "How to get 100% code coverage" Rapita Systems Ltd
 

Similar to 12 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
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
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
 
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
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
 
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)
 
"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 ...
 
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
 
.NET Foundation, Future of .NET and C#
.NET Foundation, Future of .NET and C#.NET Foundation, Future of .NET and C#
.NET Foundation, Future of .NET and C#
 
Python Exception Handling
Python Exception HandlingPython Exception Handling
Python Exception Handling
 
Presentation slides: "How to get 100% code coverage"
Presentation slides: "How to get 100% code coverage" Presentation slides: "How to get 100% code coverage"
Presentation slides: "How to get 100% code coverage"
 
Chapter 7
Chapter 7Chapter 7
Chapter 7
 
Java unit 11
Java unit 11Java unit 11
Java unit 11
 

More from maznabili

22 Methodology of problem solving
22 Methodology of problem solving22 Methodology of problem solving
22 Methodology of problem solvingmaznabili
 
21 High-quality programming code construction part-ii
21 High-quality programming code construction part-ii21 High-quality programming code construction part-ii
21 High-quality programming code construction part-iimaznabili
 
21 high-quality programming code construction part-i
21 high-quality programming code construction part-i21 high-quality programming code construction part-i
21 high-quality programming code construction part-imaznabili
 
20 Object-oriented programming principles
20 Object-oriented programming principles20 Object-oriented programming principles
20 Object-oriented programming principlesmaznabili
 
19 Algorithms and complexity
19 Algorithms and complexity19 Algorithms and complexity
19 Algorithms and complexitymaznabili
 
18 Hash tables and sets
18 Hash tables and sets18 Hash tables and sets
18 Hash tables and setsmaznabili
 
17 Trees and graphs
17 Trees and graphs17 Trees and graphs
17 Trees and graphsmaznabili
 
16 Linear data structures
16 Linear data structures16 Linear data structures
16 Linear data structuresmaznabili
 
15 Text files
15 Text files15 Text files
15 Text filesmaznabili
 
14 Defining classes
14 Defining classes14 Defining classes
14 Defining classesmaznabili
 
13 Strings and text processing
13 Strings and text processing13 Strings and text processing
13 Strings and text processingmaznabili
 
11 Using classes and objects
11 Using classes and objects11 Using classes and objects
11 Using classes and objectsmaznabili
 
10 Recursion
10 Recursion10 Recursion
10 Recursionmaznabili
 
08 Numeral systems
08 Numeral systems08 Numeral systems
08 Numeral systemsmaznabili
 
05 Conditional statements
05 Conditional statements05 Conditional statements
05 Conditional statementsmaznabili
 
04 Console input output-
04 Console input output-04 Console input output-
04 Console input output-maznabili
 
03 Operators and expressions
03 Operators and expressions03 Operators and expressions
03 Operators and expressionsmaznabili
 

More from maznabili (20)

22 Methodology of problem solving
22 Methodology of problem solving22 Methodology of problem solving
22 Methodology of problem solving
 
21 High-quality programming code construction part-ii
21 High-quality programming code construction part-ii21 High-quality programming code construction part-ii
21 High-quality programming code construction part-ii
 
21 high-quality programming code construction part-i
21 high-quality programming code construction part-i21 high-quality programming code construction part-i
21 high-quality programming code construction part-i
 
20 Object-oriented programming principles
20 Object-oriented programming principles20 Object-oriented programming principles
20 Object-oriented programming principles
 
19 Algorithms and complexity
19 Algorithms and complexity19 Algorithms and complexity
19 Algorithms and complexity
 
18 Hash tables and sets
18 Hash tables and sets18 Hash tables and sets
18 Hash tables and sets
 
17 Trees and graphs
17 Trees and graphs17 Trees and graphs
17 Trees and graphs
 
16 Linear data structures
16 Linear data structures16 Linear data structures
16 Linear data structures
 
15 Text files
15 Text files15 Text files
15 Text files
 
14 Defining classes
14 Defining classes14 Defining classes
14 Defining classes
 
13 Strings and text processing
13 Strings and text processing13 Strings and text processing
13 Strings and text processing
 
11 Using classes and objects
11 Using classes and objects11 Using classes and objects
11 Using classes and objects
 
10 Recursion
10 Recursion10 Recursion
10 Recursion
 
09 Methods
09 Methods09 Methods
09 Methods
 
08 Numeral systems
08 Numeral systems08 Numeral systems
08 Numeral systems
 
07 Arrays
07 Arrays07 Arrays
07 Arrays
 
06 Loops
06 Loops06 Loops
06 Loops
 
05 Conditional statements
05 Conditional statements05 Conditional statements
05 Conditional statements
 
04 Console input output-
04 Console input output-04 Console input output-
04 Console input output-
 
03 Operators and expressions
03 Operators and expressions03 Operators and expressions
03 Operators and expressions
 

Recently uploaded

Simplifying Mobile A11y Presentation.pptx
Simplifying Mobile A11y Presentation.pptxSimplifying Mobile A11y Presentation.pptx
Simplifying Mobile A11y Presentation.pptxMarkSteadman7
 
JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard37
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
API Governance and Monetization - The evolution of API governance
API Governance and Monetization -  The evolution of API governanceAPI Governance and Monetization -  The evolution of API governance
API Governance and Monetization - The evolution of API governanceWSO2
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMKumar Satyam
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Navigating Identity and Access Management in the Modern Enterprise
Navigating Identity and Access Management in the Modern EnterpriseNavigating Identity and Access Management in the Modern Enterprise
Navigating Identity and Access Management in the Modern EnterpriseWSO2
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
Modernizing Legacy Systems Using Ballerina
Modernizing Legacy Systems Using BallerinaModernizing Legacy Systems Using Ballerina
Modernizing Legacy Systems Using BallerinaWSO2
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 

Recently uploaded (20)

Simplifying Mobile A11y Presentation.pptx
Simplifying Mobile A11y Presentation.pptxSimplifying Mobile A11y Presentation.pptx
Simplifying Mobile A11y Presentation.pptx
 
JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptx
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
API Governance and Monetization - The evolution of API governance
API Governance and Monetization -  The evolution of API governanceAPI Governance and Monetization -  The evolution of API governance
API Governance and Monetization - The evolution of API governance
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDM
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Navigating Identity and Access Management in the Modern Enterprise
Navigating Identity and Access Management in the Modern EnterpriseNavigating Identity and Access Management in the Modern Enterprise
Navigating Identity and Access Management in the Modern Enterprise
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Modernizing Legacy Systems Using Ballerina
Modernizing Legacy Systems Using BallerinaModernizing Legacy Systems Using Ballerina
Modernizing Legacy Systems Using Ballerina
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 

12 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