Top Banner
Exceptions Handling Exceptions Handling Handling Errors during the Program Handling Errors during the Program Execution Execution Svetlin Nakov Svetlin Nakov Telerik Telerik Corporation Corporation www.telerik. com
38

12. Exceptions Handling

Sep 05, 2014

Download

Technology

Intro C# Book

What is Exception?
Catching Exceptions
Throwing Exception
The try-finally Statement
Exercises: Working with Exceptions
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: 12. Exceptions Handling

Exceptions HandlingExceptions HandlingHandling Errors during the Program Handling Errors during the Program

ExecutionExecution

Svetlin NakovSvetlin NakovTelerik Telerik

CorporationCorporationwww.telerik.com

Page 2: 12. Exceptions Handling

Table of ContentsTable of Contents

1.1. What are Exceptions?What are Exceptions?

2.2. Handling ExceptionsHandling Exceptions

3.3. The The System.ExceptionSystem.Exception Class Class

4.4. Types of Exceptions and theirTypes of Exceptions and their Hierarchy Hierarchy

5.5. Raising Raising ((ThrowingThrowing)) Exceptions Exceptions

6.6. Best PracticesBest Practices

2

Page 3: 12. Exceptions Handling

What are What are Exceptions?Exceptions?The Paradigm of Exceptions in The Paradigm of Exceptions in

OOPOOP

Page 4: 12. Exceptions Handling

What are Exceptions?What are Exceptions? The exceptions in .NET Framework are The exceptions in .NET Framework are

classic implementation of the OOP classic implementation of the OOP exception modelexception model

Deliver powerful mechanism for Deliver powerful mechanism for centralized handling of errors and centralized handling of errors and unusual eventsunusual 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 Simplify code construction and maintenancemaintenance

Allow the problematic situations to be Allow the problematic situations to be processed at multiple levelsprocessed at multiple levels 4

Page 5: 12. Exceptions Handling

Handling Handling ExceptionsExceptions

Catching and Processing ErrorsCatching and Processing Errors

Page 6: 12. Exceptions Handling

Handling ExceptionsHandling Exceptions In C# the exceptions can be handled In C# the exceptions can be handled

by theby the try-catch-finallytry-catch-finally constructionconstruction

catchcatch blocks can be used multiple blocks can be used multiple times to process different exception times to process different exception typestypes

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

Page 7: 12. Exceptions Handling

Handling Exceptions – Handling Exceptions – ExampleExample

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

Page 8: 12. Exceptions Handling

HandlinHandling g

ExceptioExceptionsnsLive DemoLive Demo

Page 9: 12. Exceptions Handling

TheThe System.ExceptionSystem.Exception ClassClass

Exceptions inExceptions in .NET .NET are objectsare objects TheThe System.ExceptionSystem.Exception class is base for class is base for

all exceptions in CLRall exceptions in CLR

Contains information for the cause of the Contains information for the cause of the error or the unusual situationerror or the unusual situation

MessageMessage – – text description of the exceptiontext description of the exception

StackTraceStackTrace – – the snapshot of the stack at the snapshot of the stack at the moment of exception throwingthe moment of exception throwing

InnerExceptionInnerException – – exception caused the exception caused the currentcurrentexception exception ((if anyif any))

9

Page 10: 12. Exceptions Handling

Exception Properties – Exception Properties – ExampleExample

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}\Console.Error.WriteLine("Exception caught: {0}\n{1}",n{1}", fe.Message, fe.StackTrace);fe.Message, fe.StackTrace); }} }}}}

10

Page 11: 12. Exceptions Handling

Exception PropertiesException Properties

TheThe MessageMessage property gives brief property gives brief description of the problemdescription of the problem

TheThe StackTraceStackTrace property is extremely property is extremely useful when identifying the reason useful when identifying the reason caused the exceptioncaused the exception

TheThe MessageMessage property gives brief property gives brief description of the problemdescription of the problem

TheThe StackTraceStackTrace property is extremely property is extremely useful when identifying the reason useful when identifying the reason caused the exceptioncaused the exceptionException caught: Input string was not in a Exception caught: Input string was not in a correct format.correct format. at System.Number.ParseInt32(String s, at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)NumberStyles style, NumberFormatInfo info) at System.Int32.Parse(String s)at System.Int32.Parse(String s) at ExceptionsTest.CauseFormatException() in c:\at ExceptionsTest.CauseFormatException() in c:\consoleapplication1\exceptionstest.cs:line 8consoleapplication1\exceptionstest.cs:line 8 at ExceptionsTest.Main(String[] args) in c:\at ExceptionsTest.Main(String[] args) in c:\consoleapplication1\exceptionstest.cs:line 15consoleapplication1\exceptionstest.cs:line 15

11

Page 12: 12. Exceptions Handling

Exception Properties Exception Properties (2)(2)

File names and line numbers are File names and line numbers are accessible only if the compilation was in accessible only if the compilation was in DebugDebug mode mode

When compiled in When compiled in ReleaseRelease mode, the mode, the information in the property information in the property StackTraceStackTrace is is quite different:quite different:

File names and line numbers are File names and line numbers are accessible only if the compilation was in accessible only if the compilation was in DebugDebug mode mode

When compiled in When compiled in ReleaseRelease mode, the mode, the information in the property information in the property StackTraceStackTrace is is quite different:quite different:Exception caught: Input string was not in a Exception caught: Input string was not in a correct format.correct format. at System.Number.ParseInt32(String s, at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)NumberStyles style, NumberFormatInfo info) at ExceptionsTest.Main(String[] args)at ExceptionsTest.Main(String[] args)

12

Page 13: 12. Exceptions Handling

Exception PropertiesException PropertiesLive DemoLive Demo

Page 14: 12. Exceptions Handling

The Hierarchy ofThe Hierarchy of ExceptionsExceptions

Page 15: 12. Exceptions Handling

Exceptions in .NET Framework are Exceptions in .NET Framework are organized in a hierarchyorganized in a hierarchy

Exception HierarchyException Hierarchy

15

Page 16: 12. Exceptions Handling

Types of ExceptionsTypes of Exceptions All .NET exceptions inherit from All .NET exceptions inherit from System.ExceptionSystem.Exception

The system exceptions inherit from The 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 User-defined exceptions should inherit from from System.ApplicationExceptionSystem.ApplicationException

16

Page 17: 12. Exceptions Handling

Handling ExceptionsHandling Exceptions

When catching an exception of a particular When catching an exception of a particular class, all its inheritors (child exceptions) are class, all its inheritors (child exceptions) are caught toocaught 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

Page 18: 12. Exceptions Handling

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 This should be lastbe last

Unreachable Unreachable codecode

Unreachable Unreachable codecode

18

Page 19: 12. Exceptions Handling

Handling All ExceptionsHandling All Exceptions

All exceptions thrown by .NET All exceptions thrown by .NET managed code inherit the managed code inherit the System.ExceptionSystem.Exception exception exception

Unmanaged code can throw other Unmanaged code can throw other exceptionsexceptions

For handling all exceptions (even For handling all exceptions (even unmanaged) use the construction:unmanaged) 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

Page 20: 12. Exceptions Handling

Throwing Throwing ExceptionsExceptions

Page 21: 12. Exceptions Handling

Throwing ExceptionsThrowing Exceptions

Exceptions are thrown (raised) by Exceptions are thrown (raised) by throwthrow keyword in C# keyword in C# Used to notify the calling code in case Used to notify the calling code in case

of error or unusual situationof error 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 The exception travels over the stack until a suitable until a suitable catchcatch block is reached to block is reached to handle ithandle it

Unhandled exceptions display error Unhandled exceptions display error messagemessage

21

Page 22: 12. Exceptions Handling

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 theprogramprogram 9. Find handler

9. Find handler

10. Display error message

10. Display error message

Page 23: 12. Exceptions Handling

Using Using throwthrow Keyword Keyword 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 if the original exception is not passed the initial cause of the exception passed the initial cause of the exception is lostis 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", throw new ArgumentException("Invalid number", fe);fe);}}

23

Page 24: 12. Exceptions Handling

Re-Throwing ExceptionsRe-Throwing Exceptions Caught exceptions can be re-Caught exceptions can be re-

thrown again: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

Page 25: 12. Exceptions Handling

Throwing Exceptions – Throwing Exceptions – ExampleExample

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

Page 26: 12. Exceptions Handling

Throwing Throwing ExceptionsExceptions

Live DemoLive Demo

Page 27: 12. Exceptions Handling

Choosing Exception Choosing Exception TypeType

27

When an invalid parameter is passed to a When an invalid parameter is passed to a method: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 If no suitable standard exception class is availableavailable

Create own exception class (inherit Create own exception class (inherit ExceptionException))

Page 28: 12. Exceptions Handling

Using Try-Finally Using Try-Finally BlocksBlocks

Page 29: 12. Exceptions Handling

TheThe try-finallytry-finally ConstructionConstruction

The construction:The construction:

Ensures execution of given block in all Ensures execution of given block in all casescases

When exception is raised or not in the When exception is raised or not in the trytry blockblock

Used for execution of cleaning-up code, Used for execution of cleaning-up code, e.g. releasing resourcese.g. releasing 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

Page 30: 12. Exceptions Handling

try-finallytry-finally – Example – Examplestatic 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 Console.WriteLine("This cleanup code is always executed.");executed."); }} Console.WriteLine("This code is after the try-finally Console.WriteLine("This code is after the try-finally block.");block.");}}

30

Page 31: 12. Exceptions Handling

Try-FinallyTry-FinallyLive DemoLive Demo

Page 32: 12. Exceptions Handling

Exceptions: Best Exceptions: Best PracticesPractices

Page 33: 12. Exceptions Handling

Best PracticesBest Practices catchcatch blocks should begin with the blocks should begin with the

exceptions lowest in the hierarchy and exceptions lowest in the hierarchy and continue with the more general continue with the more general exceptionsexceptions Otherwise a compilation error will occurOtherwise a compilation error will occur

Each Each catchcatch block should handle only block should handle only these exceptions which it expectsthese exceptions which it expects Handling all exception disregarding their Handling all exception disregarding their

type is popular bad practice!type is popular bad practice! When raising an exception always pass When raising an exception always pass

to the constructor good explanation to the constructor good explanation messagemessage

33

Page 34: 12. Exceptions Handling

BestBest Practices (Practices (22)) Exceptions can decrease the Exceptions can decrease the

application performanceapplication performance Throw exceptions only in situations Throw exceptions only in situations

which are really exceptional and which are really exceptional and should be handledshould be handled

Do not throw exceptions in the normal Do not throw exceptions in the normal program control flow (e.g.: on invalid program control flow (e.g.: on invalid user input)user input)

Some exceptions can be thrown at Some exceptions can be thrown at any time with no way to predict them, any time with no way to predict them, e.g.: e.g.: System.OutOfMemoryExceptionSystem.OutOfMemoryException

34

Page 35: 12. Exceptions Handling

SummarySummary Exceptions provide flexible error handling Exceptions 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 Each exception handler processes only errors of particular type (and its child types)errors of particular type (and its child types)

Other types of errors are processed by other Other types of errors are processed by other

handlershandlers

Unhandled exceptions cause error messagesUnhandled exceptions cause error messages

Try-finally ensures that given code block is Try-finally ensures that given code block is always executed (even when an exception always executed (even when an exception is thrown)is thrown)

35

Page 36: 12. Exceptions Handling

Exceptions HandlingExceptions Handling

Questions?Questions?

http://academy.telerik.com

Page 37: 12. Exceptions Handling

ExercisesExercises

1.1. Write a program that reads an integer Write a program that reads an integer number and calculates and prints its square number and calculates and prints its square root. If the number is invalid or negative, root. If the number is invalid or negative, print "Invalid number". In all cases finally print "Invalid number". In all cases finally print "Good bye". Use try-catch-finally.print "Good bye". Use try-catch-finally.

2.2. Write a method Write a method ReadNumber(int start, int ReadNumber(int start, int end)end) that enters an integer number in given that enters an integer number in given range [start..end]. If invalid number or non-range [start..end]. If invalid number or non-number text is entered, the method should number text is entered, the method should throw an exception. Based on this method throw an exception. Based on this method write a program that enters write a program that enters 10 10 numbers:numbers:

aa11, a, a22, … a, … a1010, such that 1 < a, such that 1 < a11 < … < < … < aa1010 < 100 < 100

37

Page 38: 12. Exceptions Handling

Exercises (2)Exercises (2)

3.3. Write a program that enters file name along Write a program that enters file name along with its full file path (e.g. with its full file path (e.g. C:\WINDOWS\win.iniC:\WINDOWS\win.ini), ), reads its contents and prints it on the console. reads its contents and prints it on the console. Find in MSDN how to use Find in MSDN how to use System.IO.File.ReadAllText(…)System.IO.File.ReadAllText(…). Be sure to . Be sure to catch all possible exceptions and print user-catch all possible exceptions and print user-friendly error messages.friendly error messages.

4.4. Write a program that downloads a file from Write a program that downloads a file from Internet (e.g. Internet (e.g. http://www.devbg.org/img/Logo-BASD.jpg) and ) and stores it the current directory. Find in Google stores it the current directory. Find in Google how to download files in C#. Be sure to catch how to download files in C#. Be sure to catch all exceptions and to free any used resources all exceptions and to free any used resources in the finally block.in the finally block. 38