Object Oriented Software Development 8. Exceptions, testing and debugging.

Slides:



Advertisements
Similar presentations
Error-handling using exceptions
Advertisements

COMPUTER PROGRAMMING I Essential Standard 5.02 Understand Breakpoint, Watch Window, and Try And Catch to Find Errors.
Chapter 3: Editing and Debugging SAS Programs. Some useful tips of using Program Editor Add line number: In the Command Box, type num, enter. Save SAS.
Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
1 Handling Exceptions COSC 1567 C++ Programming Lecture 11.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 13 Exception Handling.
C# Programming: From Problem Analysis to Program Design1 Debugging and Handling Exceptions C# Programming: From Problem Analysis to Program Design 3 rd.
 Both System.out and System.err are streams—a sequence of bytes.  System.out (the standard output stream) displays output  System.err (the standard.
Exceptions and Exception Handling Carl Alphonce CSE116 March 9, 2007.
Chapter 11 Debugging and Handling Exceptions
Chapter 12 By Tony Gaddis Modified by Elizabeth Adams Copyright © 2005 Pearson Addison-Wesley. All rights reserved.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 16: Exception Handling.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Exception Handling Topics We will discuss the following main topics: – Handling Exceptions – Throwing Exceptions – More about Input/Output Streams.
Microsoft VB 2005: Reloaded, Advanced Chapter 5 Input Validation, Error Handling, and Exception Handling.
Debugging Techniques1. 2 Introduction Bugs How to debug Using of debugger provided by the IDE Exception Handling Techniques.
Exception Handling Introduction Exception handling is a mechanism to handle exceptions. Exceptions are error like situations. It is difficult to decide.
Lecture Roger Sutton CO331 Visual programming 15: Debugging 1.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 17 Exceptions and.
Exceptions. Errors and Exceptions An error is a bug in your program –dividing by zero –going outside the bounds of an array –trying to use a null reference.
The IDE (Integrated Development Environment) provides a DEBUGGER for locating and correcting errors in program logic (logic errors not syntax errors) The.
Exception Handling An Exception is an indication of a problem that occurs during a program’s execution. Exception handling enables the programmer to create.
Exceptions Objectives At the conclusion of this lesson, students should be able to Explain the need for exceptions Correctly write programs that use.
Chapter 12: Advanced Topics: Exception Handling Visual Basic.NET Programming: From Problem Analysis to Program Design.
JavaScript, Fourth Edition
Introduction to Java Chapter 11 Error Handling. Motivations When a program runs into a runtime error, the program terminates abnormally. How can you handle.
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
Java Software Solutions Foundations of Program Design Sixth Edition
ASP.NET Programming with C# and SQL Server First Edition Chapter 6 Debugging and Error Handling.
Object Oriented Programming
Chapter 12: Exception Handling
UNIT 3 TEMPLATE AND EXCEPTION HANDLING. Introduction  Program errors are also referred to as program bugs.  A C program may have one or more of four.
COMPUTER PROGRAMMING 2 Exceptions. What are Exceptions? Unexpected events that happen when the code is executing (during runtime). Exceptions are types.
PROGRAMMING IN VISUAL BASIC.NET VISUAL BASIC BUILDING BLOCKS Bilal Munir Mughal 1 Chapter-5.
I NTRODUCTION TO PROGRAMMING Starting Out with Java: From Control Structures through Objects CS 146 Class Notes Fall 10.
Java Software Solutions Lewis and Loftus Chapter 14 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Advanced Flow of Control --
VB.Net - Exceptions Copyright © Martin Schray
1 Software Construction and Evolution - CSSE 375 Exception Handling - Principles Steve Chenoweth, RHIT Above – Exception handling on the ENIAC. From
Testing and Debugging Version 1.0. All kinds of things can go wrong when you are developing a program. The compiler discovers syntax errors in your code.
Introduction to Exception Handling and Defensive Programming.
1 Κατανεμημένες Διαδικτυακές Εφαρμογές Πολυμέσων Γιάννης Πετράκης.
Controlling Execution Programming Right from the Start with Visual Basic.NET 1/e 8.
Making Good Code AKA: So, You Wrote Some Code. Now What? Ray Haggerty July 23, 2015.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
FT228/3 Web Development Error processing. Introduction READ Chapter 9 of Java Server Pages from O’reilly 2 nd Edition Need to be able to 1) Diagnose and.
PROGRAMMING IN VISUAL BASIC.NET VISUAL BASIC PROGRAMMING FUNDAMENTALS Bilal Munir Mughal 1 Chapter-8.
Exceptions and Assertions Chapter 15 – CSCI 1302.
CS212: Object Oriented Analysis and Design Lecture 19: Exception Handling.
CSCI 383 Object-Oriented Programming & Design Lecture 20 Martin van Bommel.
Error Handling Tonga Institute of Higher Education.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
Exceptions Lecture 11 COMP 401, Fall /25/2014.
IMS 3253: Validation and Errors 1 Dr. Lawrence West, MIS Dept., University of Central Florida Topics Validation and Error Handling Validation.
C# Exceptions 1 CNS 3260 C#.NET Software Development.
Defensive Programming. Good programming practices that protect you from your own programming mistakes, as well as those of others – Assertions – Parameter.
Exceptions in OO Programming Introduction Errors Exceptions in Java Handling exceptions The Try-Catch-Finally mechanism Example code Exception propagation.
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
Introduction to Exceptions in Java CS201, SW Development Methods.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Enhanced Car Payment Calculator Application Introducing Exception Handling.
Debugging and Handling Exceptions
Testing and Debugging.
Computer Programming I
Exceptions Problems in a Java program may cause exceptions or errors representing unusual or invalid processing. An exception is an object that defines.
Exception Handling Chapter 9 Edited by JJ.
Part B – Structured Exception Handling
Testing, debugging, and using support libraries
Exception Handling Imran Rashid CTO at ManiWeber Technologies.
Exceptions References: Jacquie Barker, Beginning Java Objects; Rick Mercer, Computing Fundamentals With Java; Wirfs-Brock et. al., Martin Fowler, OOPSLA.
Chapter 11: Exception Handling
Presentation transcript:

Object Oriented Software Development 8. Exceptions, testing and debugging

Writing 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 Object Oriented Software Development 8. Exceptions, testing and debugging 2

Support 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 Object Oriented Software Development 8. Exceptions, testing and debugging 3

Run-time 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 Object Oriented Software Development 8. Exceptions, testing and debugging 4

What are exceptions? In C# (and other languages) when a run-time error occurs an exception is generated Usually say exception is thrown An exception is an object that contains information about a run-time error Exception-handling involves writing code which is executed when an exception is thrown Interrupts normal flow of execution Object Oriented Software Development 8. Exceptions, testing and debugging 5

Exceptions examples SimpleExceptions project Program.cs InfoSaver.cs Object Oriented Software Development 8. Exceptions, testing and debugging 6

Exception handling This code tries to open a file Will cause an error if the file does not exist Object Oriented Software Development 8. Exceptions, testing and debugging 7 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 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

try-catch block Wrap code in try block and catch exception Catch block can print message, log error, etc. Object Oriented Software Development 8. Exceptions, testing and debugging 8

Multiple catch blocks Exception classes are all derived from Exception Can catch different exception types Usually catch most specific first Object Oriented Software Development 8. Exceptions, testing and debugging 9 this will catch any exception as all exceptions derive from Exception

System 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 Object Oriented Software Development 8. Exceptions, testing and debugging 10

Cleaning up afterwards Object Oriented Software Development 8. Exceptions, testing and debugging close file normally – this code might not be reached could get exception while writing data even of file opens successfully finally block will always execute need to declare resource outside try block so that it is in scope in finally block

Should we catch exception immediately? Wrapping code in try-catch 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 Object Oriented Software Development 8. Exceptions, testing and debugging 12

Exceptions 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 Object Oriented Software Development 8. Exceptions, testing and debugging 13

Options 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 Object Oriented Software Development 8. Exceptions, testing and debugging 14

Passing on an exception Object Oriented Software Development 8. Exceptions, testing and debugging 15 method in class, does not handle exception method in class, does not handle exception calling method, in Main class, handles exception and reports it to user

Exceptions and the call stack Object Oriented Software Development 8. Exceptions, testing and debugging 16 If no suitable exception handler is found, program will exit due to unhandled exception

Throwing a new exception Object Oriented Software Development 8. Exceptions, testing and debugging 17 may want to log exception then create a new exception object to pass on to calling class then create a new exception object to pass on to calling class

Cleaning up (again) Difficult for calling class to clean up resources used by called method Can use try-finally 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 Object Oriented Software Development 8. Exceptions, testing and debugging 18

Cleaning up with using Object Oriented Software Development 8. Exceptions, testing and debugging 19 resources opened here will be closed properly even if exception occurs inside using block, as long as resource class implements IDisposable interface

Don’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 conditions for example, check whether the number is zero before dividing Object Oriented Software Development 8. Exceptions, testing and debugging 20 archive/2009/08/04/exceptions- the-airbags-of-code.aspx

Throwing 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 Object Oriented Software Development 8. Exceptions, testing and debugging 21

A 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 Object Oriented Software Development 8. Exceptions, testing and debugging 22

Custom exception examples CustomException project Account.cs OverdrawnException.cs Object Oriented Software Development 8. Exceptions, testing and debugging 23

OverdrawnException class Object Oriented Software Development 8. Exceptions, testing and debugging 24 can pass relevant information into exception object

Throwing the exception Exception is thrown in Withdraw method of Account class if rule violated Object Oriented Software Development 8. Exceptions, testing and debugging 25

Why 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 Object Oriented Software Development 8. Exceptions, testing and debugging 26

Handling exception in UI Object Oriented Software Development 8. Exceptions, testing and debugging 27 this code runs when Withdraw button is clicked – initial balance is £100 can handle other exceptions here too

Testing 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 Object Oriented Software Development 8. Exceptions, testing and debugging 28

Unit testing The process of testing individual classes is known as unit testing Continuous process during, and even before, development Test-Driven Development process involves writing tests first, then developing code until tests are passed There is support for unit testing in most modern languages Object Oriented Software Development 8. Exceptions, testing and debugging 29

Unit 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 Object Oriented Software Development 8. Exceptions, testing and debugging 30

Unit testing example OrderSystem project Order.cs Object Oriented Software Development 8. Exceptions, testing and debugging 31

Visual Studio test project Create Unit Tests option in Visual Studio Allows you to select what to test By default, creates a separate test project Object Oriented Software Development 8. Exceptions, testing and debugging 32

Test 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 Object Oriented Software Development 8. Exceptions, testing and debugging 33

Test method Object Oriented Software Development 8. Exceptions, testing and debugging 34 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

Running tests Object Oriented Software Development 8. Exceptions, testing and debugging 35 two tests in this test run – one has failed

Bugs 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 Object Oriented Software Development 8. Exceptions, testing and debugging 36

Bug-tracking Teams often use bug-tracking 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 Object Oriented Software Development 8. Exceptions, testing and debugging 37

Debugging 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 line-by-line and watch the values of variables which may help diagnose the cause of the problem Most IDEs include debugging tools Object Oriented Software Development 8. Exceptions, testing and debugging 38

Example The unit test for CalcPrice in Order failed – set a breakpoint in this method and debug Choose Debug rather than Start Without Debugging Object Oriented Software Development 8. Exceptions, testing and debugging 39 click in margin to set breakpoint – program halts which it reaches first breakpoint

Debugger 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 Object Oriented Software Development 8. Exceptions, testing and debugging 40

Watching variables Enter variable names in Watch window Locals window shows all variables in scope Can “dig into” structure of objects Object Oriented Software Development 8. Exceptions, testing and debugging 41 OrderLine object, includes LinePrice, Product, Quantity properties Product is an object, includes Name, Price, ProductID properties

Quick 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 Object Oriented Software Development 8. Exceptions, testing and debugging 42

Debugging 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 Object Oriented Software Development 8. Exceptions, testing and debugging 43

What’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 Object Oriented Software Development 8. Exceptions, testing and debugging 44