Question? Leave a message!

Exceptions, testing and debugging

Exceptions, testing and debugging
Object Oriented Software Development 8. Exceptions, testing and debugging WWW.ThesisScientist.comWriting high quality software  Programs should handle unexpected error conditions in a controlled way  Report or log error as appropriate  Don’t “crash”  Programs should be thoroughly tested  Prove that requirements are met  Program can run without error but still produce incorrect behaviour  Continuous testing of “units” of code and integration of units throughout development WWW.ThesisScientist.comSupport for the programmer  Exception handling in programming language provides a way to deal with error conditions  Unit testing tools provide support for continuous testing  Debugging tools provide support for tracing through code as it runs to diagnose error conditions or incorrect behaviour WWW.ThesisScientist.comRuntime errors  “Anything that can go wrong, will go wrong” (Murphy’s law)  Many things can, and do, go wrong when a computer program runs, for example when it:  attempts to open a file that doesn’t exist  tries to convert a string to a numeric type  performs a calculation which divides by zero  tries to send a message to a null object reference  If error is not handled, program will crash WWW.ThesisScientist.comWhat are exceptions  In C (and other languages) when a runtime error occurs an exception is generated  Usually say exception is thrown  An exception is an object that contains information about a runtime error  Exceptionhandling involves writing code which is executed when an exception is thrown  Interrupts normal flow of execution WWW.ThesisScientist.comExceptions examples  SimpleExceptions project  Program.cs  InfoSaver.cs WWW.ThesisScientist.comException handling  This code tries to open a file  Will cause an error if the file does not exist this code opens access to a file (FileStream) and creates an object which can write to the file (StreamWriter) closing the StreamWriter also closes the FileStream WWW.ThesisScientist.comtrycatch block  Wrap code in try block and catch exception  Catch block can print message, log error, etc. WWW.ThesisScientist.comMultiple catch blocks  Exception classes are all derived from Exception  Can catch different exception types  Usually catch most specific first this will catch any exception as all exceptions derive from Exception WWW.ThesisScientist.comSystem resources  Files, database connections, etc are system resources  Should be closed when no longer needed  Exception occurring can prevent code which closes resources being reached  Resources not released back to system  Files can become unavailable, system can become unstable, etc.  Need to clean up resources after exceptions WWW.ThesisScientist.comCleaning up afterwards could get exception while writing data even of file opens successfully close file normally – this code ... might not be reached finally block will always execute need to declare resource outside try block so that it is in scope in finally block WWW.ThesisScientist.comShould we catch exception immediately  Wrapping code in trycatch means exception is handled immediately  This will prevent program crashing, but may not be the most useful behaviour  For example, does the user need to know about the error  We don’t necessarily want to suppress error  Can opt to handle exception elsewhere, e.g. in user interface code WWW.ThesisScientist.comExceptions in class library code  Class library code may be used by many different programs  Each program may have its own way of making users aware of error situations or of logging errors  Class library code should not usually handle exceptions completely  Should pass them onto program to handle WWW.ThesisScientist.comOptions for handling an exception  Handle the exception condition immediately  Pass on the unhandled exception to the calling class  Handle and rethrow the exception to be handled by the calling class  Throw a new exception to be handled by the calling class WWW.ThesisScientist.comPassing on an exception method in class, does not handle exception calling method, in Main class, handles exception and reports it to user WWW.ThesisScientist.comExceptions and the call stack If no suitable exception handler is found, program will exit due to unhandled exception WWW.ThesisScientist.comThrowing a new exception may want to log exception then create a new exception object to pass on to calling class WWW.ThesisScientist.comCleaning up (again)  Difficult for calling class to clean up resources used by called method  Can use tryfinally in called method  Doesn’t catch exception, but finally block will always execute even if exception occurs  More convenient shorthand for this in C with using key word  Other languages have similar constructs WWW.ThesisScientist.comCleaning up with using resources opened here will be closed properly even if exception occurs inside using block, as long as resource class implements IDisposable interface WWW.ThesisScientist.comDon’t overuse exceptions  Handling exceptions incurs overhead, so only use exceptions to deal with exceptional situations  a state that occurs infrequently or unexpectedly  Check for predictable error archive/2009/08/04/exceptions theairbagsofcode.aspx conditions  for example, check whether the number is zero before dividing WWW.ThesisScientist.comThrowing your own exceptions  You can use the exceptions mechanism to indicate and handle error conditions which don’t crash the program, but do break your program’s business rules  For example:  Invalid password entered  Attempt to withdraw more than specified limit from a bank account WWW.ThesisScientist.comA custom exception class  Exception class to be used by a bank account class  OverdrawnException class, derived from Exception  Business rule is that customer cannot withdraw an amount which would leave a negative balance in the account  Exception is used to indicate a situation where this rule has been violated WWW.ThesisScientist.comCustom exception examples  CustomException project  Account.cs  OverdrawnException.cs WWW.ThesisScientist.comOverdrawnException class can pass relevant information into exception object WWW.ThesisScientist.comThrowing the exception  Exception is thrown in Withdraw method of Account class if rule violated WWW.ThesisScientist.comWhy throw an exception  Account class could choose to simply not perform the withdrawal if rule violated  That wouldn’t alert the user to the problem or give the user an opportunity to correct it  However, Account class cannot, and should not, communicate with the user  Throws exception which the user interface can handle in its own way WWW.ThesisScientist.comHandling exception in UI this code runs when Withdraw button is clicked – initial balance is £100 can handle other exceptions here too WWW.ThesisScientist.comTesting  Software must be comprehensively tested to check that it meets the specified requirements and works correctly  Different types of testing meet different purposes as development proceeds, e.g.:  Integration testing as major components are put together  System testing against specification  Alpha/Beta testing before release by members of target user community  Unit testing WWW.ThesisScientist.comUnit testing  The process of testing individual classes is known as unit testing  Continuous process during, and even before, development  TestDriven Development process involves writing tests first, then developing code until tests are passed  There is support for unit testing in most modern languages WWW.ThesisScientist.comUnit testing  Tests should be written to exercise the significant behaviour of all classes  Unit tests can be repeated as we continue to develop each class and integrate classes  Make sure that we don’t inadvertently break a part of a class which was working correctly  Make sure changing one class does not break another class which depends on it  This is known as regression testing WWW.ThesisScientist.comUnit testing example  OrderSystem project  Order.cs WWW.ThesisScientist.comVisual Studio test project  Create Unit Tests option in Visual Studio  Allows you to select what to test  By default, creates a separate test project WWW.ThesisScientist.comTest class  By default, has a name based on name of class to be tested  Order OrderTest  Each test is defined by a test method  Basic code for test methods is generated, but needs to be edited to create meaningful tests  Success/failure defined with Assert statements WWW.ThesisScientist.comTest method this test creates an Order with two lines – we don’t need to set all attributes of related objects as the calculation only uses the customer discount and product prices test will pass if expected = actual, and fail otherwise WWW.ThesisScientist.comRunning tests two tests in this test run – one has failed WWW.ThesisScientist.comBugs  Situations where a program does not behave as expected are known as bugs  Can be errors which halt the program or simply incorrect behaviour  All forms of testing can discover bugs  Most bugs should be discovered before release but fixing bugs is also part of post release maintenance WWW.ThesisScientist.comBugtracking  Teams often use bugtracking systems  Testers can report bugs they discover  Each bug is assigned to a particular developer to resolve  Developer records resolution of each bug  Often used with version control  Central copy of code, each developer “checks out” a part to work on and “checks in” new code  All versions kept, can roll back and define numbered builds and release versions WWW.ThesisScientist.comDebugging  Testing can find bugs, but doesn’t fix them  Developer must examine code to find source of error or test failure  Debugger is a tool which allows you to break program execution at a specific point, step through code linebyline and watch the values of variables which may help diagnose the cause of the problem  Most IDEs include debugging tools WWW.ThesisScientist.comExample  The unit test for CalcPrice in Order failed – set a breakpoint in this method and debug  Choose Debug rather than Start Without click in margin to set breakpoint – program Debugging halts which it reaches first breakpoint WWW.ThesisScientist.comDebugger options  Continue – go on to next breakpoint if any more are set  Stop Debugging – end execution immediately  Step Into – go to next statement, if statement is method call then go to first line of method  Step Over – go to next statement, do not step into a called method  Step Out – run to end of current method and stop at next statement of calling method WWW.ThesisScientist.comWatching variables  Enter variable names in Watch window  Locals window shows all variables in scope  Can “dig into” structure of objects OrderLine object, includes LinePrice, Product, Quantity properties Product is an object, includes Name, Price, ProductID properties WWW.ThesisScientist.comQuick watch  Visual Studio also allows you to hover the cursor over any variable which is in scope where the execution is stopped, and its value is shown WWW.ThesisScientist.comDebugging in practice  Tools help, but experience helps more  Need to be able to understand the program  Need to identify most useful place in program to set breakpoints  Need to identify critical variables to watch  If bug symptom is an error, experience of common exceptions and error messages can help identify likely causes WWW.ThesisScientist.comWhat’s next  You now know how to write robust C classes to implement the model for a system. You will go on learn how to create a graphical user interface which allows people to interact with the system
Document Information
User Name:
User Type:
Uploaded Date: