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
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
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
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
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