Similar presentations

2 Chapter ObjectivesLearn about exceptions, including how they are thrown and caughtGain an understanding of the different types of errors that are found in programsLook at debugging methods available in Visual StudioDiscover how the Debugger can be used to find run-time errors

3 Chapter Objectives (continued)Become aware of and use exception- handling techniques to include try…catch…finally clausesExplore the many exception classes and learn how to write and order multiple catch clauses

4 Error message does not always state the correct problemErrorsVisual Studio IDE reports errors as soon as it is able to detect a problemSyntax errorsLanguage rule violationError message does not always state the correct problemQuick infoFigure 11-1 Syntax error – extraneous semicolon

5 Run-Time ErrorsJust because your program reports no syntax errors does not necessarily mean it is running correctlyOne form of run-time error is a logic errorProgram runs, but produces incorrect resultsMay be off-by-one in a loopSometime users enter incorrect valuesFinding the problem can be challenging

6 Debugging in C# Desk check Many IDEs have DebuggersDebuggers let you observer the run-time behaviorYou can break or halt executionYou can step through the applicationYou can evaluate variablesYou can set breakpointsDebug menu offers debugging options

8 Debugging in C# (continued)Select Start Debugging and number of options to run your program doublesFigure 11-3 Debug menu options during debugging mode

9 BreakpointsMarkers placed in an application, indicating the program should halt execution when it reaches that pointBreak modeExamine expressionsCheck intermediate resultsUse Debug menu to set BreakpointF9 (shortcut)Toggles

13 Debugging in C# Continue Stepping through codeTakes the program out of break mode and restores it to a run-time modeIf more than one breakpoint set, Continue causes the program to execute from the halted line until it reaches the next breakpointStepping through codeExecute code line by line and see the execution pathExamine variable and expression values as they change

14 Stepping Through Code Step Into (F11) Step Over (F10)Program halts at the first line of code inside the called methodStep Over (F10)Executes the entire method called before it haltsStep Out (Shift+F11)Causes the rest of the program statements in the method to be executed and then control returns to the method that made the call

15 Watches Can set Watch windows during debugging sessionsWatch window lets you type in one or more variables or expressions to observe while the program is runningWatch window differs from Locals window, which shows all variables currently in scopeQuick Watch option on Debug menu lets you type a single variable or expression

17 What if you don’t have VS?Many of the results of the features in VS can be replicated by debugging using code.Much harder to do with code than with VS debugging featuresDebugging in the codeWriteLines to report location where code isReport Variables

18 Exceptions Some circumstances are beyond programmer’s controlYou have assumed nothing unusual would occurHave probably experienced unhandled exceptions being thrownWhile you browsed Web pagesWhile you were developing applications using C#Unless provisions are made for handling exceptions, your program may crash or produce erroneous resultsUnhandled exception

19 Exceptions (continued)Dialog box asks you whether you want to have an error report sent to MicrosoftFigure 11-9 Microsoft error reporting

20 Exceptions (continued)Normally you do not want to try to debug application while it is runningClick NoFigure Just-In-Time Debugger

21 Unhandled ExceptionMessage displayed when you are creating console application and unhandled exception occursFigure Unhandled exception in a console application

23 Raising an Exception Error encountered – no recoveryRaise or throw an exceptionExecution halts in the current method and the Common Language Runtime (CLR) attempts to locate an exception handlerException handler: block of code to be executed when a certain type of error occursIf no exception handler is found in current method, exception is thrown back to the calling method

24 Bugs, Errors, and ExceptionsBugs differ from exceptionsBugs, also called "programmer mistakes," should be caught and fixed before application releasedErrors can be created because of user actionsExampleEntering wrong type of data produces unhandled exception when ParseInt( ) calledDetails button in Visual Studio lists a stack trace of methods with the method that raised the exception listed first

26 Exception-Handling TechniquesIf event creates a problem frequently, best to use conditional expressions to catch and fix problemExecution is slowed down when CLR has to halt a method and find an appropriate event handlerException-handling techniques are for serious errors that occur infrequentlyExceptions classes integrated within the FCLUsed with the try…catch…finally program constructs

27 Try…Catch…Finally BlocksCode that may create a problem is placed in the try blockCode to deal with the problem (the exception handler) is placed in catch blocksCatch clauseCode to be executed whether an exception is thrown or not is placed in the finally block

29 Try…Catch…Finally Blocks (continued)Generic catch clauseOmit argument list with the catchAny exception thrown is handled by executing code within that catch blockControl is never returned into the try block after an exception is thrownUsing a try…catch block can keep the program from terminating abnormally

31 What Caused These Exceptions to be Thrown?Never quite sure what causes theexception to be thrown when a generic catch clause is used!Figure Exceptions – division by zero and programmer error

32 Exception Object When an exception is raised, an object is createdObject has properties and behaviors (methods)Catch clause may list an exception classCatch { } without exception type does not give you access to an objectBase exception class: ExceptionMessage property returns a string describing exceptionStackTrace property returns a string that contains the called trace of methods

34 Exception ClassesApplicationException and SystemException classes form the basis for run-time exceptions

35 Exception Classes (continued)ApplicationExceptionDerive from this class when you write your own exception classesUser program must throw the exception, not the CLRSystemExceptionMost run-time exceptions derive from this classSystemException class adds no functionality to classes; includes no additional properties or methods

38 System.DivideByZeroExceptionDerived class of System.ArithmeticException classThrown when an attempt to divide by zero occursOnly thrown for integral or integer data typesFloating-point operands do not throw an exceptionResult reported as either positive infinity, negative infinity, or Not-a-Number (NaN)Follows the rules from IEEE 754 arithmetic

39 Filtering Multiple ExceptionsCan include multiple catch clausesEnables writing code specific to thrown exceptionShould be placed from most specific to the most genericIf Exception class is included, it should always be placed last

40 Custom Exceptions Derive from the ApplicationException classGood idea to use the word “Exception” as part of the identifierCreating an exception class is no different from creating any other class

43 Custom Exceptions (continued)Throwing a programmer-defined exceptionException object is instantiated when "an exceptional condition occurs”Can be any condition, but should be one that happens infrequentlyAfter object is instantiated, object is thrown

45 Input Output (IO) ExceptionsSystem.IO.IOExceptionDirect descendent of ExceptionThrown when a specified file or directory is not foundThrown when program attempts to read beyond the end of a fileThrown when there are problems loading or accessing the contents of a file