Chapter 1 Introduction to C++: Name space: Defines an area in which names have scope. Can use the same name in different name spaces. Header file (file.

Slides:



Advertisements
Similar presentations
Topics Introduction Types of Errors Exceptions Exception Handling
Advertisements

Exception Handling The purpose of exception handling is to permit the program to catch and handle errors rather than letting the error occur and suffer.
CSE 332: C++ exceptions Overview of C++ Exceptions Normal program control flow is halted –At the point where an exception is thrown The program call stack.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 16: Exception Handling.
Exception Handling Introduction Exception handling is a mechanism to handle exceptions. Exceptions are error like situations. It is difficult to decide.
Chapter 15 Memory Management: Four main memory areas for a C++ program: Code: code for instructions, methods, etc. static data: Global variables (declared.
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
© Copyright Eliyahu Brutman Programming Techniques Course Version 1.0.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
Slides prepared by Rose Williams, Binghamton University Chapter 9 More Exception Handling.
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
Introduction to Classes and Objects CS-2303, C-Term Introduction to Classes and Objects CS-2303 System Programming Concepts (Slides include materials.
Chapter 7. 2 Objectives You should be able to describe: The string Class Character Manipulation Methods Exception Handling Input Data Validation Namespaces.
CS-2303 System Programming Concepts
Basic Elements of C++ Chapter 2.
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.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
Review of C++ Programming Part II Sheng-Fang Huang.
Programming Languages and Paradigms Object-Oriented Programming.
June 14, 2001Exception Handling in Java1 Richard S. Huntrods June 14, 2001 University of Calgary.
CPSC 252 Exception Handling Page 1 Exceptions and exception handling Client programmers can make errors using a class attempting to dequeue an item from.
Handling ErrorstMyn1 Handling Errors Up to this point we haven't worried much about errors or exceptions. First, let's distinguish between errors and exceptions.
C++ Exceptions STL Vector. Example int Quotient (int numer, int denom} { if (denom != 0) return (numer/denom); else //What to do?? }
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.
Chapter 6 Vectors and arrays: Arrays: Run the following code. Anything unusual? #include using namespace std; #define N 10 #define M 11 int main() { int.
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
Program A computer program (also software, or just a program) is a sequence of instructions written in a sequence to perform a specified task with a computer.
Classes CS 21a: Introduction to Computing I First Semester,
Chapter 13. Procedural programming vs OOP  Procedural programming focuses on accomplishing tasks (“verbs” are important).  Object-oriented programming.
Introduction to Exception Handling and Defensive Programming.
Copyright  Hannu Laine C++-programming Part 1 Hannu Laine.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
Chapter 10 Introduction to Classes
1 Program Input Software Design Chapter 4. 2 You Will Want to Know... Prompting for and reading values into a program. Accessing data from a file. What.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 16: Introduction to C++
2 Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
Exceptions and Assertions Chapter 15 – CSCI 1302.
CSE 332: C++ Statements C++ Statements In C++ statements are basic units of execution –Each ends with ; (can use expressions to compute values) –Statements.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
CS212: Object Oriented Analysis and Design Lecture 19: Exception Handling.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Today: –Review declaration, implementation, simple class structure. –Add an exception class and show.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
Chapter 9: Completing the Basics. In this chapter, you will learn about: – Exception handling – Exceptions and file checking – The string class – Character.
Programming & Debugging. Key Programming Issues Modularity Modifiability Ease of Use Fail-safe programming Style Debugging.
11 Introduction to Object Oriented Programming (Continued) Cats.
A FIRST BOOK OF C++ CHAPTER 14 THE STRING CLASS AND EXCEPTION HANDLING.
C++ Programming Lecture 14 Arrays – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
1 Introduction to Object Oriented Programming Chapter 10.
Recap Introduction to Inheritance Inheritance in C++ IS-A Relationship Polymorphism in Inheritance Classes in Inheritance Visibility Rules Constructor.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
C++ Namespaces, Exceptions CSci 588: Data Structures, Algorithms and Software Design All material not from online sources copyright © Travis Desell, 2011.
Exception Handling How to handle the runtime errors.
EE4E. C++ Programming Lecture 6 Advanced Topics. Contents Introduction Introduction Exception handling in C++ Exception handling in C++  An object oriented.
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.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Chapter 1.2 Introduction to C++ Programming
Chapter Topics The Basics of a C++ Program Data Types
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Completing the Problem-Solving Process
Basic Elements of C++.
Why exception handling in C++?
Basic Elements of C++ Chapter 2.
Exceptions with Functions
Class rational part2.
Chapter 1 c++ structure C++ Input / Output
CMSC 202 Exceptions.
Introduction to Classes and Objects
Presentation transcript:

Chapter 1 Introduction to C++: Name space: Defines an area in which names have scope. Can use the same name in different name spaces. Header file (file with a.h extension) files included in the compilation of a program. Usually contain types, definitions and declarations, but not executable code. Source file (file with a.cpp extension) contains source code to be compiled.

Always back up source and header files (frequently)!!! Demo01. Note that compiling a program creates very large files. Also demo02 shows how a gui can be set up. This will NOT be a focal point of the class.

Chapter 2 Numbers and objects: Data types float, int (32-bit in VC++.NET), double (64-bit float) Operators +, -, *, /, ++, --, %, etc. NOTE: Do not use % with negative integers; it’s different from the strict mathematic definition of % (modulus).

Most of this is similar to Java. More on cin, cout. can input multiple nos with one cin but it’s not recommended. String input – does not read spaces. int input – make sure NOT to input a float number. The fractional part is ignored and remains in the buffer. endl is a newline for output streams.

static casting – see page const qualifier for variables. Always use in place of actual numbers. DO NOT USE magic numbers (p. 53). enumerated types Similar to constant ints in java. See book example page 54.

Math functions Need: #include for Visual studio. Might be #include in other environments. See page 58 for math functions. string types. Need #include Demos have examples. See also p

Always initialize variables. Use meaningful variable names. Use // for short comments. Use /* and */ pair for lengthy or frequently changing comments. Always use a readable code layout. Indent, format, use visual separators, align (code and output). See demos

Chapter 5 Designing and writing a class: A class has two parts Interface (in a header file) and implementation (in a cpp file). Chapter 5 does not show this initially, but it should be done!

Interface: Variable definitions, constructors, and method signatures. How the user interacts with the class. Implementation: Code for the methods.

Method types: Every method identified in the interface must be defined in the implementation. See chapter 5 and demos for syntax. Mutator: method that changes the object state. Accessor: method that is not a Mutator. Should have a const qualifier (p. 239). See potential problem on p. 240.

Constructors Default constructor has no parameters. Examples on page 241. Or Build your own constructors with parameters (p. 244). You should always write a default constructor!! They are used if a class variable is declared. Example, the following will NOT compile:

#include using namespace std; class Test { public: Test (int value); int getdata() { return data; } private: int data; }; Test::Test(int value) { data = value; } int main() { Test x; Test y(5); cout << x.getdata() << endl; cin.get(); return 0; }

There are two possible solutions: Write a second constructor, Test::Test() and set data to a default value Modify the above by writing Test::Test(int value = 0)

NOTE: prose on page 241. MUST initialize numeric data fields. A string would automatically be instantiated as an empty string. If the previous example also contained a string variable, it would NOT need to be specified in the parameter list.

When two methods have the same name but different parameter sets, the function name is overloaded.

Caution: Consider the example void funtest(int i, double d) { cout << "\n\nfuntest(int i, double d) called."; cout << "\nPar1 i = " << i << " ; Par2 d = " << d << endl; } void funtest(double d, int i) { cout << "\n\nfuntest(double d, int i) called."; cout << "\nPar1 d = " << d << " ; Par2 i = " << i << endl; }

Include the following in main. Show what happens when comments are removed. Why? funtest(1.2, 5); funtest(3,5.5); //funtest(4, 5);

Destructors. Called when object goes out of scope. Different from Java - you will need to write destructors. Get in the habit of doing so now.

Same issues with private/public (encapsulation) as you saw in the Java courses. implicit and explicit parameters: an explicit parameter is identified in the method name. An implicit parameter is the object specified when the method was called.

Accessors should always have a const qualifier. Recall the example on page 240. DO NOT call a constructor for an object a second time. i.e. do not explicitly invoke a constructor on an existing object. CAN call constructors of other classes from a constructor (page 247-8). Elaborate on Advance Topic 5.1 (p. 247) and note the field initializer list.

Design the Investment class of Demo03. Section 5.8 discusses non-member functions, functions that are not members of any class. I will periodically use for illustrative purposes and sometimes in test harnesses. However, when using OOD, it’s best to NOT use them. Section 5.9 discusses header files.

Book Notes Watch for missing and extraneous semicolons. Sometimes the compiler generates a message several lines beyond where it occurred. Do not mix >> and getline input commands. Do not mix << and printf output commands. See the random fact on p. 243.

Chapter 17 Exception Handling: Exception: loose definition – a situation for which normal activities cannot proceed. Can be caused by: bad data, incorrect inputs, non-existent files, impossible tasks (divide by 0, square root of a negative number), etc. Issues: Who must deal with them and how?

Book example Stack class with methods: push, top, pop, and size. Designed by programmer P1 Application that uses stack designed by programmer P2. What if there is an attempt to pop an empty stack and the application aborts?

P1 provides the ability to check for it and argues P2 used the stack improperly. P2 argues P1 should have anticipated such problems. Stack class would be more reliable and robust if there were a better error checking mechanism. Programmers should not make assumptions regarding the user -- probably should also not make assumptions about other programmers who use their code.

See quality Tip p Some traditional ways to deal with errors: Printing error messages in certain conditions. Limited use: not always useful in production runs where there is no user watching the screen or real-time software where a user interaction takes too long. What if the user does not understand the language in which the message is printed?

Common example method to calculate a square root displays a message if the incoming parameter is negative. This is a bad design. flight controller error handler message “incoming plane altitude too low – press enter to continue”

Using functions to return error codes. Of course, application must still check it. Also function may already be designed to return something (an object, for instance). See common error p External flags: See examples on page 672.

What if you had y = sqrt(atoi(x)) where x is a string. Each of atoi and sqrt can generate a different errno? Another reason why global variables are not good. assert command. Causes program to halt under certain conditions. This is not always desirable. See p. 673.

Error handler functions Uses a pointer to a function to handle errors when they occur. See p. 673 and code snippet from the next slide.

#include using namespace std; int eh1() {cout << "input is a negative number" << endl; return 1; } int eh2() {cout << "input is 0" << endl; return 2; } int (*test())() {float x; cin >> x; if (x==0) { return eh2; } if (x<0) { return eh1; } } int main() { int (*f) (); f = test(); (*f) (); cin.get(); return 0; }

Exception handling is the more accepted way of dealing with problems. Similar to Java exceptions. General form: try { code } catch (type1 e1) { code } catch (type2 e2) { code } : : catch (typen en) { code } Somewhere in the try (or in methods called from the try there must be a throw exception command.

Example try/catch code below. logic_error(“string”) is a standard exception class declared in. float x; cin >> x; try { if ( x < 0 ) throw logic_error("negative value"); } catch (logic_error& e) { cout << "Error: " << e.what() << endl; cin.get(); exit (0); } cout cin.get(); return 0;

Can throw and catch anything, but special error classes are typical Might look at example on p. 677, but don’t do this! Look at demo03 investment program with exceptions built into it. Note: two different types of exceptions (invalid numeric data and invalid characters in the input). Note also the locations of the throw instructions.

Can build derived exception classes from base exception classes. See standard exception hierarchy on p Demo03 has an alternative definition for the AppError class that is a derived class. Can change comments to use or remove it. Why do this? See p. 678.

Can use a catch clause using three dots (catch(…)) to mean “all remaining exceptions”. Note common error p If an exception is thrown AFTER dynamically creating memory the handler MUST remember to free it. Or else you have memory leaks!! This will be relevant later in this course!!

Can specify in method declaration exactly what exceptions a method can actually throw. See syntax on p Improper exception handling caused an ESA (European Space Agency) rocket to explode in See the quality tips and random facts on p

Where to catch and throw exceptions: Example (sqrt method) Double sqrt(double x) { Try { if (x < 0) Throw exception } Catch exception { Some logic }

What is wrong with this? Sqrt method is written to be used by others Coder of sqrt is deciding what to do when exception is thrown. In effect the coder is speaking for those who want to use the method.

Application may be calling sqrt for a value input from a keyboard. In that case may want to re-input. for a value input from a file. In that case, may want to skip data. for a value generated elsewhere. In that case, may want to perform alternative logic.

Rule of thumb: Throw exception at the deepest level of program code as possible – at the very last possible place where the error must be checked Catch the exception at the highest level possible – closest to the application that uses the code. Let’s the user of the service decide what to do when errors occur.