C# Exceptions Handling

38
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

Transcript of C# Exceptions Handling

Page 1: C# Exceptions Handling

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

ExecutionExecution

Svetlin NakovSvetlin NakovTelerik Telerik

CorporationCorporationwww.telerik.com

Page 2: C# Exceptions Handling

Table of ContentsTable of Contents1.1. What are Exceptions?What are Exceptions?2.2. Handling ExceptionsHandling Exceptions3.3. The The System.ExceptionSystem.Exception Class Class4.4. Types of Exceptions and theirTypes of Exceptions and their

Hierarchy Hierarchy5.5. Raising Raising ((ThrowingThrowing)) Exceptions Exceptions6.6. Best PracticesBest Practices

2

Page 3: C# Exceptions Handling

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

OOPOOP

Page 4: C# 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 centralized Deliver 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 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: C# Exceptions Handling

Handling Handling ExceptionsExceptionsCatching and Processing ErrorsCatching and Processing Errors

Page 6: C# 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 construction construction

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: C# 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: C# Exceptions Handling

HandlinHandling g

ExceptioExceptionsnsLive DemoLive Demo

Page 9: C# Exceptions Handling

TheThe System.ExceptionSystem.Exception ClassClass

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

exceptions in CLRexceptions 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: C# 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: C# 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 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: C# 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: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: C# Exceptions Handling

Exception PropertiesException PropertiesLive DemoLive Demo

Page 14: C# Exceptions Handling

The Hierarchy ofThe Hierarchy of ExceptionsExceptions

Page 15: C# 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: C# 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 from User-defined exceptions should inherit from System.ApplicationExceptionSystem.ApplicationException

16

Page 17: C# 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: C# 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: C# 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: C# Exceptions Handling

Throwing Throwing ExceptionsExceptions

Page 21: C# 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 until The exception travels over the stack until

a suitable 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: C# 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 the1. Execute theprogram

program 9. Find handler

9. Find handler

10. Display error message10. Display error message

Page 23: C# 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: C# 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: C# 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: C# Exceptions Handling

Throwing Throwing ExceptionsExceptions

Live DemoLive Demo

Page 27: C# 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: C# Exceptions Handling

Using Try-Finally Using Try-Finally BlocksBlocks

Page 29: C# Exceptions Handling

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

Page 30: C# 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: C# Exceptions Handling

Try-FinallyTry-FinallyLive DemoLive Demo

Page 32: C# Exceptions Handling

Exceptions: Best Exceptions: Best PracticesPractices

Page 33: C# 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: C# 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: C# 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 errors Each exception handler processes only errors

of particular type (and its child types)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: C# Exceptions Handling

Exceptions HandlingExceptions Handling

Questions?Questions?

http://academy.telerik.com

Page 37: C# Exceptions Handling

ExercisesExercises1.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 < … < a < … < a1010 < 100 < 100

37

Page 38: C# 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 catch . Be sure to catch all possible exceptions and print user-friendly all possible exceptions and print user-friendly error messages.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 all how to download files in C#. Be sure to catch all exceptions and to free any used resources in exceptions and to free any used resources in the finally block.the finally block.

38