CSCE 121:509-512 Introduction to Program Design and Concepts Dr. J. Michael Moore Spring 2015 Set 7: Errors 1 Based on slides created by Bjarne Stroustrup.

Slides:



Advertisements
Similar presentations
Chapter 5 Errors Bjarne Stroustrup
Advertisements

Topics Introduction Types of Errors Exceptions Exception Handling
An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 15: Exception Handling.
Chapter 16: Exception Handling C++ Programming: From Problem Analysis to Program Design, Fifth Edition.
Objectives In this chapter you will: Learn what an exception is Learn how to handle exceptions within a program See how a try / catch block is used to.
 Both System.out and System.err are streams—a sequence of bytes.  System.out (the standard output stream) displays output  System.err (the standard.
Chapter 8Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 8 l Basic Exception Handling »the mechanics of exceptions l.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 16: Exception Handling.
Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Errors Lecture 6 Hartmut Kaiser
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Computer Programming and Basic Software Engineering 4. Basic Software Engineering 1 Writing a Good Program 4. Basic Software Engineering 3 October 2007.
Rossella Lau Lecture 9, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 9: Application with Exception Handling 
CS 201 Functions Debzani Deb.
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
Exceptions Objectives At the conclusion of this lesson, students should be able to Explain the need for exceptions Correctly write programs that use.
C++ fundamentals.
Introduction To C++ Programming 1.0 Basic C++ Program Structure 2.0 Program Control 3.0 Array And Structures 4.0 Function 5.0 Pointer 6.0 Secure Programming.
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.
Exceptions COMPSCI 105 S Principles of Computer Science.
Lecture 4 Errors Bjarne Stroustrup
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
CPSC 252 Exception Handling Page 1 Exceptions and exception handling Client programmers can make errors using a class attempting to dequeue an item from.
CIS 270—Application Development II Chapter 13—Exception Handling.
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.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
Chapter 5: Control Structures II (Repetition)
Slides adapted from: Bjarne Stroustrup, Programming – Principles and Practice using C++ Chapter 5 Errors Hartmut Kaiser
IPC144 Introduction to Programming Using C Week 1 – Lesson 2
CSCE 121: Introduction to Program Design and Concepts, Honors Dr. J. Michael Moore Spring 2015 Set 3: Objects, Types, and Values 1 Based on slides.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
Exceptions Handling Exceptionally Sticky Problems.
1 Debugging. 2 A Lot of Time is Spent Debugging Programs Debugging. Cyclic process of editing, compiling, and fixing errors. n Always a logical explanation.
Chapter 14: Exception Handling. Objectives In this chapter, you will: – Learn what an exception is – Learn how to handle exceptions within a program –
CPS120: Introduction to Computer Science Decision Making in Programs.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
BIO Java 1 Exception Handling Aborting program not always a good idea – can’t lose messages – E-commerce: must ensure correct handling of private.
1 Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
Slides adapted from: Bjarne Stroustrup, Programming – Principles and Practice using C++ Chapter 6 Writing a Program Hartmut Kaiser
CSCE 121: Introduction to Program Design and Concepts Dr. J. Michael Moore Spring 2015 Set 4: Computation 1 Based on slides created by Bjarne Stroustrup.
Computer Programming with JAVA Chapter 8. Exception Handling Basic Exception Handling the mechanics of exceptions Defining and Using Exceptions some "simple"
1 Debugging and Syntax Errors in C++. 2 Debugging – a process of finding and fixing bugs (errors or mistakes) in a computer program.
Exceptions Chapter 16 This chapter explains: What as exception is Why they are useful Java exception facilities.
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
CSE 332: C++ Statements C++ Statements In C++ statements are basic units of execution –Each ends with ; (can use expressions to compute values) –Statements.
Chapter 15: Exception Handling C++ Programming: Program Design Including Data Structures, Fifth Edition.
CSC 143A 1 CSC 143 Introduction to C++ [Appendix A]
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
CS116 COMPILER ERRORS George Koutsogiannakis 1. How to work with compiler Errors The Compiler provide error messages to help you debug your code. The.
Programming & Debugging. Key Programming Issues Modularity Modifiability Ease of Use Fail-safe programming Style Debugging.
CSCE 121: Introduction to Program Design and Concepts Dr. J. Michael Moore Spring Fall 2016 Set 10: Input/Output Streams 1 Based on slides created.
Exception Handling How to handle the runtime errors.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
CSCE Introduction to Program Design and Concepts J. Michael Moore Spring 2015 Set 6: Miscellaneous 1 Based on slides created by Bjarne Stroustrup.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
Introduction to Exceptions in Java CS201, SW Development Methods.
C++ Exceptions.
Exceptions.
Handling Exceptionally Sticky Problems
Testing and Debugging.
Errors Lecture 6 Hartmut Kaiser
Chapter 14: Exception Handling
Bjarne Stroustrup Chapter 5 Errors Bjarne Stroustrup
Exception Handling Chapter 9.
Exception Handling Chapter 9 Edited by JJ.
Handling Exceptionally Sticky Problems
Presentation transcript:

CSCE 121: Introduction to Program Design and Concepts Dr. J. Michael Moore Spring 2015 Set 7: Errors 1 Based on slides created by Bjarne Stroustrup and Jennifer Welch

CSCE 121: Set 7: Errors Outline Kinds of errors Function argument checking – Error reporting – Error detection – Exceptions Debugging Testing 2

CSCE 121: Set 7: Errors Errors Errors are natural and unavoidable when writing programs Organize software to minimize errors Eliminate most of the errors we made through testing and debugging Ensure remaining errors are not serious Avoiding, finding, and correcting errors is 95% of effort for serious software development 3

CSCE 121: Set 7: Errors Your Programs Should produce desired result for all legal inputs Should give reasonable error messages for illegal inputs Need not worry about misbehaving hardware Need not worry about misbehaving system software Is allowed to terminate after finding an error 4

CSCE 121: Set 7: Errors Sources of Error Poor specification Incomplete programs Unexpected arguments Unexpected input … 5

CSCE 121: Set 7: Errors Kinds of Errors Compile-time errors – Syntax errors – Type errors Link-time errors (can’t find other parts) Run-time errors – Detected by computer => crash – Detected by library => exception – Detected by user code Logic error – Detected by programmer (or user) => code runs but produces wrong output 6

CSCE 121: Set 7: Errors Check Your Inputs Before trying to use an input value, make sure it meets your expectations/requirements – Function arguments – Data from input stream 7

CSCE 121: Set 7: Errors Bad Function Arguments The compiler helps – Number and types of arguments must match 8 int area(int length, int width) { return length*width;} … int x1 = area(7); //error; wrong number of args int x2 = area(“seven”,2); // error; first arg has wrong type int x3 = area(7,10); // ok int x4 = area(7.5,10); // ok but dangerous (7.5 => 7) int x5 = area(10,-7); // types are correct but nonsensical

CSCE 121: Set 7: Errors Bad Function Arguments What to do about area(10,-7) ? Caller should check – Hard to do systematically Function should check 1.Return an “error value”, or 2.Set an error status indicator, or 3.Throw an exception 9

CSCE 121: Set 7: Errors Returning an Error Value Caller must check: if (area(x,y) < 0) cout << “error”; Problems: – What if caller forgets to check? – For some values, there is no bad value to return (e.g., max) 10 int area(int length, int width) { if (length <= 0 || width <= 0) return -1; return length*width; }

CSCE 121: Set 7: Errors Setting an Error Status Indicator Caller must check: int z = area(x,y); if (errno == 7) cout << “bad area computation”; Problems: – What if caller forgets to check? – How to choose a unique value for errno? – How does caller deal with the error? 11 int errno = 0; // global variable int area(int length, int width) { if (length <= 0 || width <= 0) errno = 7; return length*width }

CSCE 121: Set 7: Errors Throwing an Exception Special syntax for dealing with errors When an error situation is encountered, code invokes a throw statement Associated with the throw statement is an object containing more information (can be of user-defined type) – the exception When throw is executed, control is returned to the calling function together with the thrown object 12

CSCE 121: Set 7: Errors Catching an Exception Calling function should have the call to the throwing function enclosed in a try statement At the end of the try statement is one (or more) catch clauses Each catch clause has an argument and some code that will be executed if an exception is thrown inside the try and the thrown object has the matching type – This is the error-handling code! Execution resumes after the catch clause 13

CSCE 121: Set 7: Errors Exception Example 14 class Bad_area {}; // user-defined type to be used // for making exception objects int area(int length, int width) { if (length <= 0 || width <= 0) throw Bad_area(); // make an unnamed Bad_area object return length*width; } … try { int z = area(x,y); } catch(Bad_area) { // parameter is an unnamed Bad_area object cerr << “Oops! Bad area calculation – fix program\n”; } …

CSCE 121: Set 7: Errors Exceptions Exception handling is general – You cannot forget about an exception: program will terminate if the exception is not handled – Just about every kind of error can be reported using exceptions You still have to figure out what to do about an exception 15

CSCE 121: Set 7: Errors Out-of-Range Exceptions When using std_lib_facilities_4.h, vector will throw a Range_error exception if you use an invalid index The default behavior does not ensure this though! Mechanism is in std_lib_facilities_4.h for pedagogical purposes 16

CSCE 121: Set 7: Errors Exceptions – For Now For now, just use exceptions to terminate programs gracefully, like this: 17 int main() try { // your program here } catch(out_of_range) { // out of range exceptions cerr << “oops, some vector index is out of range\n”; } catch(…) { // all other exceptions cerr << “oops, some other exception\n”; }

CSCE 121: Set 7: Errors Utility error Function Provided in std_lib_facilities_4.h Combines two tasks: – Allows you to print an error message of your choosing – Throws a runtime error so that program halts 18 void error(string s) { // make an unnamed object of type runtime_error with // parameter s (string that can be accessed in catch clause) throw runtime_error(s); // throw the object made }

CSCE 121: Set 7: Errors Using error See using-error.cpp 19

CSCE 121: Set 7: Errors How to Find Errors Make the program easy to read! Comments – explain design ideas Use meaningful names Indent consistently Break code into small functions (at most a page) Avoid complicated code sequences if possible (such as nested loops, nested if-statements) Use library facilities 20

CSCE 121: Set 7: Errors Common Compile-Time Errors String literal not terminated cout << “Hello, << name << ‘\n’; Character literal not terminated cout << “Hello, “ << name << ‘\n; Block not terminated if (a > 0) { /* do something */ else { /* do something else */} Mismatched parentheses if (a x = f(y); 21

CSCE 121: Set 7: Errors More Common Compile-Time Errors Name not declared before it’s used Needed headers not included Name spelled incorrectly (case matters) Expression statement not terminated with a semicolon 22

CSCE 121: Set 7: Errors Debugging Carefully follow the program through its sequence of steps Add debug output statements to check intermediate results and see where you are Check what the program actually says, not what you think it says for (int i=0; 0 < month.size(); ++i) { … } for (int i=0; i <= max; ++j) { … } 23

CSCE 121: Set 7: Errors Debugging: Corner Cases Is every variable initialized? Did the function get the right values? Did you handle the first / last element correctly? Did you handle the empty case correctly? Did you open the files correctly? Did you actually read that input? 24

CSCE 121: Set 7: Errors Preconditions What does a function require of its arguments? Such a requirement is called a precondition Often a good idea to check if the requirement holds Example: arguments to area function should be positive. 25

CSCE 121: Set 7: Errors Postconditions What must be true when a function returns? Such a condition is called a postcondition Example: area function must return a positive integer that is the product of its arguments 26

CSCE 121: Set 7: Errors Pre- and Postconditions Always think about what they should be for each function you write At a minimum, put them in comments for the function Check them where “reasonable” Check a lot when debugging 27

CSCE 121: Set 7: Errors Testing Be systematic and extensive Test parts of program in isolation – When you’ve written a complicated function, write a little program that just calls it to see how it behaves in isolation before putting it into the real program 28

CSCE 121: Set 7: Errors Acknowledgments Photo on slide 1: “Games Bank Error” by Chris Potter, licensed under CC BY 2.0: “Games Bank ErrorChris PotterCC BY 2.0 Slides are based on those for the textbook: 29