CS102 C++ Exception Handling & Namespaces

Size: px
Start display at page:

Download "CS102 C++ Exception Handling & Namespaces"

Transcription

1 CS102 C++ Exception Handling & Namespaces Bill Cheng 1

2 Topics to cover C Structs (Ch 10) C++ Classes (Ch 11) Constructors Destructors Member functions Exception Handling (Ch 15) Namespaces (Ch 8) Operator Overloading (Ch 14) Class Composition & Inheritance (Ch 12) Pointers & Dynamic Objects (Ch 13) Polymorphism (Ch 13) Virtual functions Abstract classes Interfaces C++ Object-Oriented Programming 2

3 Exception Handling When something goes wrong in one of your functions, how should you notify to the function caller? Return a special value from the function? Return a bool indicating success/failure? Set a global variable? Print out an error message? Print an error and exit the program? Set a failure flag on somewhere (like "cin" does)? Handle the problem and just don t tell the caller? 3

4 Exception Handling There s something wrong with all those options... You should always notify the caller something happened. Silence is not an option. You can t always return an error state (what if a function is supposed to return "bool"?) What if something goes wrong in a Constructor? You don t have a return value available What if the function where the error happens isn t equipped to handle the error? All these strategies are passive. They require the caller to actively check if something went wrong. 4

5 The "assert" Statement The assert statement allows you to make sure certain conditions are true and immediately halt your program if they re not Good sanity checks for development/testing Not ideal for an end product #include <cassert> int divide(int num, int denom) assert(denom!= 0); return(num/denom); 5

6 The "throw" Statement Used when code has encountered a problem, but the current code can t handle that problem itself #include <cassert> int divide(int num, int denom) if(denom == 0) throw denom; return(num/denom); throw interrupts the normal flow of execution If nothing deals with it, the program will terminate Gives the caller the opportunity to catch and handle it What can you give to the throw statement? Anything! But some things are better than others... 6

7 What Should You "throw"? Don t throw primitive values (e.g. an "int") throw 123; The value that is thrown may not always be meaningful Provides no other context (what happened & where?) Don t throw "string" throw "Someone passed in a 0 and stuff broke!"; Works for a human, but not much help to an application Use the <stdexcept> header file throw std::invalid_argument( "Denominator can t be 0!"); Serves as the basis for building your own exceptions Have a method called "what()" with extra details You can always make your own exception class too! 7

8 The "try" and "catch" Statements try & catch are the companions to throw A try block surrounds any code that may throw A catch block lets you handle exceptions if a throw does happen (you can have multiple catch blocks) try divide(numerator,denominator); catch(int& badvalue) cerr << "Can t use value " << badvalue << endl; //do other stuff 8

9 The "try/catch" Flow try cout << "This code is fine." << endl; throw 0; //some code that always throws cout << "This will never print." << endl; catch(int& x) cerr << "The throw immediately comes here." << endl; catch(string& y) cerr << "We won t hit this catch." << endl; cout << "Everything goes back to normal here." << endl; This example just illustrates functionality...it s not that useful 9

10 cin Error Handling (the Old Way) #include <iostream> using namespace std; int main() int number = 0; cout << "Enter a number: "; cin >> number; if(cin.fail()) cerr << "That was not a number." << endl; cin.clear(); cin.ignore(1000, \n ); 10

11 cin Error Handling (the New Way) #include <iostream> using namespace std; int main() //tell "cin" it should throw cin.exceptions(iostream::failbit); //or cin.exceptions(istream::failbit); //or cin.exceptions(ios::failbit); //or cin.exceptions(ios_base::failbit); int number = 0; try cout << "Enter a number: "; cin >> number; catch(iostream::failure &ex) cerr << "That was not a number." << endl; cin.clear(); cin.ignore(1000, \n ); cout << "number = " << number << endl; 11

12 Vector Indexing (the Old Way) #include <iostream> #include <vector> using namespace std; int main() int index = -1; vector<int> list(5,0); if(index < 0 index >= list.size()) cerr << "Your index was out of range!" << endl; else cout << "Value is: " << list[index] << endl; 12

13 Vector Indexing (the New Way) #include <iostream> #include <vector> #include <stdexcept> using namespace std; int main() int index = -1; vector<int> list(5,0); try cout << "Value is: " << list[index] << endl; catch(out_of_range &ex) cerr << "Your index was out of range!" << endl; 13

14 Advantages/Disadvantages The Good Give the function caller a choice on how (or if) they want to handle an error Don t assume you know what the caller wants Decouple the exception processing logic from the normal control flow of the code They make for much cleaner code (usually) Exceptions can propagate up the call hierarchy ("Unwinding the call stack") Exceptions are sort of "duct taped" onto C++ The Bad Hard to tell if/when a function will throw Being able to throw things like "int" isn t very useful 14

15 Other throw/try/catch Notes Do not use throw from a destructor. Your code will go into an inconsistent (and unpleasant) state. Or just crash. You can use the catch(...) (a.k.a. catch everything) statement to catch any exception, but it s usually not that desirable try //code that throws something catch(...) cerr << "I got an error, but I have no context!" << endl; 15

16 Other "throw/try/catch" Notes You can re-throw an exception you ve caught Useful if you want to take intermediate action, but can t actually handle the exception try //code that throws something catch(someexception& se) cerr << "I got an error!" << endl; throw; //throws "se" again from here 16

17 Notes On Exams Now that you know about exceptions In exams, when you detect an error condition, you should know that you can just throw an exception Please don t say, "I assume that an error condition cannot happen" Please don t ask, "What should I do about error conditions?" <stdexcept> Logic errors logic_error domain_error invalid_argument length_error out_of_range Runtime errors runtime_error range_error overflow_error underflow_error 17

18 CS102 C++ Namespaces Bill Cheng 18

19 Namespaces A high-level grouping mechanism for class, function and variable definitions NOTE: Only applies to things declared at the global level (e.g. not variables within functions) Why do we need them? Avoid naming conflicts Especially when using #include with other people s stuff Group related functionality Example: Spreadsheet for a furniture store Table of Tables 19

20 Defining Namespaces How do we declare a namespace? namespace SOME_NAME //code goes here By default, everything is in the global namespace If you declare the same namespace block multiple times (e.g. "namespace XYZ... ") then everything will be merged into one big namespace You already know that most everything in <iostream> is declared in the namespace "std" 20

21 Putting Namespaces to Use Namespaces are used with the "scope resolution operator" (a.k.a. the "::") The default global namespace is just "::" It s assumed if you don t specify it Prefix your item with "name::" to use a namespace std::cout << "Blah blah blah" << std::endl; This should look really similar to defining functions for a class Classes are an implicit namespacing/scoping mechanism! 21

22 The "using" Statement Normally you always have to use an item s namespace std::cout << "Hello world!" << std::endl; The using keyword lets you pull thing out of other namespaces into your current namespace You can pull individual items in: using std::cout; cout << "Hello world!" << std::endl; You can pull the entire namespace in (be careful!): using namespace std; cout << "Hello world!" << endl; Don t specify using in your header (.h) files! (bad style don t assume you know what others want) 22

23 CS102 Extra Slides Bill Cheng 23

24 assert.cpp /* * 1) Create a function divide(). It asserts that denominator * cannot be 0. * 2) In main() read in two integers and call divide() and * print the return value. * 3) If would not compile, probably because forgot to * #include <cassert>. */ 24

25 #include <iostream> #include <cassert> using namespace std; int divide(int num,int denom) assert(denom!= 0); return(num/denom); int main() int n,d; cout << "Enter: "; cin >> n >> d; assert.cpp cout << "Result = " << divide(n,d) << endl; 25

26 throw.cpp /* * 1) Demonstrate how to use throw, try & catch. * 2) Show how to make your own exception class. * 3) Create a class DivideByZeroError to throw. (Cannot * inherit this from one of the existing exception * class because we haven t covered exception yet.) * 4) Write the divide() function. If denominator is 0, * throw an instance of class above. If any of the * input is negative, throw the out_of_range system * exception. * 5) Write a function foo() that calls divide() using try * and catch. Make it so that it will only catch the * out_of_range exception. * 6) In main(), read two integers, calls foo() in the * try block and have 3 catch blocks. One to catch * out_of_range, one to catch DivideByZeroError, and * one to catch everything else. * 7) Print the return value of foo(). * 8) Try entering values like "10 2", "10 0" and "10-2" from * the console to see the different behaviors. * 9) If would not compile, probably because forgot to * #include <stdexcept>. */ 26

27 #include <iostream> #include <string> #include <stdexcept> #include <vector> using namespace std; class DivideByZeroError public: DivideByZeroError() ; throw.cpp int divide(int num,int denom) if(denom == 0) DivideByZeroError err; throw err; //alternate syntax: //throw DivideByZeroError; else if(num < 0 denom < 0) throw out_of_range("negative values."); return(num/denom); int foo(int num,int denom) try return divide(num,denom); catch(out_of_range& oor) cerr << "In foo() = " << oor.what() << endl; 27

28 int main() int n,d; cout << "Enter: "; cin >> n >> d; throw.cpp (Cont...) int result; try result = foo(n,d); cout << "Still in the try block after foo..." << endl; catch(out_of_range& oof) cerr << "in main() = " << oof.what() << endl; catch(dividebyzeroerror& ex) cerr << "We divided by zero!" << endl; catch(...) //this statement is never triggered in this code, but it s //the syntax for a "catch all" that will catch anything that //gets thrown from within the "try" block cout << "Result = " << result << endl; 28

29 namespaces.cpp /* * 1) Demonstrate how to use namespace. * 2) Don t do "using namespace std"; * 3) Note that most things in "iostream" and "string" are * in the namespace "std" by default. * 4) Define a global int variable y. This is in the * default namespace. * 5) Create a namespace called cs102. Define a class Dummy * in it with a method called bar() that returns a * std::string. * 6) Using a separate namespace block to put more stuff * into the cs102 namespace. Define a function foo() * to use std::cout and std::endl. * 7) In main(), do "using std::endl;" so that we can just * say "endl" without pulling the whole std namespace * into main(). * 8) Define an int named cout and print it. * 9) Call foo() from the cs102 namespace. * 10) Create an instance of Dummy and call its bar() member * function. * 12) Create a local int variable y. Print the local * variable y. Print the global variable y in the * default namespace. */ 29

30 #include <iostream> #include <string> int y = 0; namespace cs102 class Dummy std::string bar() ; return "this is bar()"; namespace cs102 void foo() namespaces.cpp int main() using std::endl; int cout = 5; std::cout << cout << endl; cs102::foo(); cs102::dummy d; std::cout << d.bar() << endl; int y = 99; std::cout << y << endl; std::cout << ::y << endl; std::cout << "foo() is in the " << "cs102 namespace" << std::endl; 30

CSCI 104 Exceptions. Mark Redekopp David Kempe

CSCI 104 Exceptions. Mark Redekopp David Kempe CSCI 104 Exceptions Mark Redekopp David Kempe Code for Today On your VM: $ mkdir except $ cd except $ wget http://ee.usc.edu/~redekopp/cs104/except.tar $ tar xvf except.tar 2 Recall Remember the List ADT

More information

CSCI 104 Classes. Mark Redekopp David Kempe

CSCI 104 Classes. Mark Redekopp David Kempe CSCI 104 Classes Mark Redekopp David Kempe CLASSES 2 C Structs Needed a way to group values that are related, but have different data types NOTE: struct has changed in C++! C C++ Only data members Some

More information

CS11 Advanced C++ Fall Lecture 3

CS11 Advanced C++ Fall Lecture 3 CS11 Advanced C++ Fall 2006-2007 Lecture 3 Today s Topics C++ Standard Exceptions Exception Cleanup Fun with Exceptions Exception Specifications C++ Exceptions Exceptions are nice for reporting many errors

More information

Object-Oriented Principles and Practice / C++

Object-Oriented Principles and Practice / C++ Object-Oriented Principles and Practice / C++ Alice E. Fischer June 8, 2015 OOPP / C++ Lecture 7... 1/20 Program Errors Error Handling Techniques Exceptions in C++ Exception Definition Syntax Throwing

More information

CSCI 102L - Data Structures Midterm Exam #1 Fall 2011

CSCI 102L - Data Structures Midterm Exam #1 Fall 2011 Print Your Name: Page 1 of 8 Signature: Aludra Loginname: CSCI 102L - Data Structures Midterm Exam #1 Fall 2011 (10:00am - 11:12am, Wednesday, October 5) Instructor: Bill Cheng Problems Problem #1 (24

More information

! Errors can be dealt with at place error occurs

! Errors can be dealt with at place error occurs UCLA Stat 1D Statistical Computing and Visualization in C++ Instructor: Ivo Dinov, Asst. Prof. in Statistics / Neurology University of California, Los Angeles, Winter 200 http://www.stat.ucla.edu/~dinov/courses_students.html

More information

Throwing exceptions 02/12/2018. Throwing objects. Exceptions

Throwing exceptions 02/12/2018. Throwing objects. Exceptions ECE 150 Fundamentals of Programming Outline 2 In this lesson, we will: See that we can throw objects Know that there are classes defined in the standard template library These classes allow more information

More information

void fun() C::C() // ctor try try try : member( ) catch (const E& e) { catch (const E& e) { catch (const E& e) {

void fun() C::C() // ctor try try try : member( ) catch (const E& e) { catch (const E& e) { catch (const E& e) { TDDD38 APiC++ Exception Handling 134 Exception handling provides a way to transfer control and information from a point in the execution to an exception handler a handler can be invoked by a throw expression

More information

Practice test for midterm 3 solutions

Practice test for midterm 3 solutions Practice test for midterm 3 solutions May 5, 2 18 1 Classes Here is a pair of class definitions, and a pair of variable declarations: class A { int x; float y; ; class B { int y; A a; float x; A b; ; A

More information

Laboratorio di Tecnologie dell'informazione

Laboratorio di Tecnologie dell'informazione Laboratorio di Tecnologie dell'informazione Ing. Marco Bertini marco.bertini@unifi.it http://www.micc.unifi.it/bertini/ Exceptions What are exceptions? Exceptions are a mechanism for handling an error

More information

CSC 330 Object-Oriented Programming. Exception Handling CSC 330

CSC 330 Object-Oriented Programming. Exception Handling CSC 330 Object-Oriented Programming Exception Handling 1 C++ Exception Handling Topics Exception Handling C++ Exception Handling Basics Throwing and Catching Exceptions Constructors, Destructors and Exceptions

More information

Intermediate Programming, Spring 2017*

Intermediate Programming, Spring 2017* 600.120 Intermediate Programming, Spring 2017* Misha Kazhdan *Much of the code in these examples is not commented because it would otherwise not fit on the slides. This is bad coding practice in general

More information

C++ Crash Kurs. Exceptions. Dr. Dennis Pfisterer Institut für Telematik, Universität zu Lübeck

C++ Crash Kurs. Exceptions. Dr. Dennis Pfisterer Institut für Telematik, Universität zu Lübeck C++ Crash Kurs Exceptions Dr. Dennis Pfisterer Institut für Telematik, Universität zu Lübeck http://www.itm.uni-luebeck.de/people/pfisterer C++ Exceptions: Introduction What are exceptions Exceptions are

More information

Exception Handling Pearson Education, Inc. All rights reserved.

Exception Handling Pearson Education, Inc. All rights reserved. 1 16 Exception Handling 2 16.1 Introduction Exceptions Indicate problems that occur during a program s execution Occur infrequently Exception handling Can resolve exceptions Allow a program to continue

More information

Exception Handling Pearson Education, Inc. All rights reserved.

Exception Handling Pearson Education, Inc. All rights reserved. 1 16 Exception Handling 2 I never forget a face, but in your case I ll make an exception. Groucho Marx It is common sense to take a method and try it. If it fails, admit it frankly and try another. But

More information

Exception Handling in C++

Exception Handling in C++ Exception Handling in C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by

More information

IS 0020 Program Design and Software Tools

IS 0020 Program Design and Software Tools 1 Introduction 2 IS 0020 Program Design and Software Tools Exception Handling Lecture 12 November 23, 200 Exceptions Indicates problem occurred in program Not common An "exception" to a program that usually

More information

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program: Welcome Back CSCI 262 Data Structures 2 - Review What you learned in CSCI 261 (or equivalent): Variables Types Arrays Expressions Conditionals Branches & Loops Functions Recursion Classes & Objects Streams

More information

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program: Welcome Back CSCI 262 Data Structures 2 - Review What you learned in CSCI 261 (or equivalent): Variables Types Arrays Expressions Conditionals Branches & Loops Functions Recursion Classes & Objects Streams

More information

Introduction. Common examples of exceptions

Introduction. Common examples of exceptions Exception Handling Introduction Common examples of exceptions Failure of new to obtain memory Out-of-bounds array subscript Division by zero Invalid function parameters Programs with exception handling

More information

Assertions and Exceptions

Assertions and Exceptions CS 247: Software Engineering Principles Assertions and Exceptions Reading: Eckel, Vol. 2 Ch. 1 Exception Handling U Waterloo CS247 (Spring 2017) p.1/32 Defensive Programming The question isn t whether

More information

COMP6771 Advanced C++ Programming

COMP6771 Advanced C++ Programming 1.... COMP6771 Advanced C++ Programming Week 5 Part One: Exception Handling 2016 www.cse.unsw.edu.au/ cs6771 2.... Memory Management & Exception Handling.1 Part I: Exception Handling Exception objects

More information

Lecture 10. To use try, throw, and catch Constructors and destructors Standard exception hierarchy new failures

Lecture 10. To use try, throw, and catch Constructors and destructors Standard exception hierarchy new failures Lecture 10 Class string Exception Handling To use try, throw, and catch Constructors and destructors Standard exception hierarchy new failures Class template auto_ptr Lec 10 Programming in C++ 1 Class

More information

Intermediate Programming, Spring 2017*

Intermediate Programming, Spring 2017* 600.120 Intermediate Programming, Spring 2017* Misha Kazhdan *Much of the code in these examples is not commented because it would otherwise not fit on the slides. This is bad coding practice in general

More information

C++ Primer for CS175

C++ Primer for CS175 C++ Primer for CS175 Yuanchen Zhu September 10, 2014 This primer is pretty long and might scare you. Don t worry! To do the assignments you don t need to understand every point made here. However this

More information

17.1 Handling Errors in a Program

17.1 Handling Errors in a Program Chapter 17: Exceptions From the board game MONOPOLY, the rule to follow when your man lands on the illegal square: Go to jail. Go directly to jail, do not pass GO and do not collect $200. 17.1 Handling

More information

CSE 303: Concepts and Tools for Software Development

CSE 303: Concepts and Tools for Software Development CSE 303: Concepts and Tools for Software Development Hal Perkins Autumn 2008 Lecture 24 Introduction to C++ CSE303 Autumn 2008, Lecture 24 1 C++ C++ is an enormous language: All of C Classes and objects

More information

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010 CSE 374 Programming Concepts & Tools Hal Perkins Spring 2010 Lecture 19 Introduction ti to C++ C++ C++ is an enormous language: g All of C Classes and objects (kind of like Java, some crucial differences)

More information

05-01 Discussion Notes

05-01 Discussion Notes 05-01 Discussion Notes PIC 10B Spring 2018 1 Exceptions 1.1 Introduction Exceptions are used to signify that a function is being used incorrectly. Once an exception is thrown, it is up to the programmer

More information

CPSC 427: Object-Oriented Programming

CPSC 427: Object-Oriented Programming CPSC 427: Object-Oriented Programming Michael J. Fischer Lecture 19 November 7, 2018 CPSC 427, Lecture 19, November 7, 2018 1/18 Exceptions Thowing an Exception Catching an Exception CPSC 427, Lecture

More information

Chapter 5 Errors. Hyunyoung Lee. Based on slides by Bjarne Stroustrup.

Chapter 5 Errors. Hyunyoung Lee. Based on slides by Bjarne Stroustrup. Chapter 5 Errors Hyunyoung Lee Based on slides by Bjarne Stroustrup www.stroustrup.com/programming 1 Abstract When we program, we have to deal with errors. Our most basic aim is correctness, but we must

More information

CS3157: Advanced Programming. Outline

CS3157: Advanced Programming. Outline CS3157: Advanced Programming Lecture #12 Apr 3 Shlomo Hershkop shlomo@cs.columbia.edu 1 Outline Intro CPP Boring stuff: Language basics: identifiers, data types, operators, type conversions, branching

More information

CS 162, Lecture 25: Exam II Review. 30 May 2018

CS 162, Lecture 25: Exam II Review. 30 May 2018 CS 162, Lecture 25: Exam II Review 30 May 2018 True or False Pointers to a base class may be assigned the address of a derived class object. In C++ polymorphism is very difficult to achieve unless you

More information

Engineering Tools III: OOP in C++

Engineering Tools III: OOP in C++ Engineering Tools III: OOP in C++ Engineering Tools III: OOP in C++ Why C++? C++ as a powerful and ubiquitous tool for programming of numerical simulations super-computers (and other number-crunchers)

More information

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++ CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 19 Introduction to C++ C++ C++ is an enormous language: All of C Classes and objects (kind of like Java, some crucial differences) Many

More information

Exceptions. CS162: Introduction to Computer Science II. Exceptions. Exceptions. Exceptions. Exceptions. Exceptions

Exceptions. CS162: Introduction to Computer Science II. Exceptions. Exceptions. Exceptions. Exceptions. Exceptions CS162: Introduction to Computer Science II A typical way to handle error conditions is through the return value. For example, suppose we create a loadfile() function that returns true if it loaded the

More information

Unit 4 Basic Collections

Unit 4 Basic Collections Unit 4 Basic Collections General Concepts Templates Exceptions Iterators Collection (or Container) Classes Vectors (or Arrays) Sets Lists Maps or Tables C++ Standard Template Library (STL Overview A program

More information

C++ Exception Handling 1

C++ Exception Handling 1 C++ Exception Handling 1 An exception is a problem that arises during the execution of a program. A C++ exception is a response to an exceptional circumstance that arises while a program is running, such

More information

Errors. Lecture 6. Hartmut Kaiser hkaiser/fall_2011/csc1254.html

Errors. Lecture 6. Hartmut Kaiser  hkaiser/fall_2011/csc1254.html Hartmut Kaiser hkaiser@cct.lsu.edu http://www.cct.lsu.edu/ hkaiser/fall_2011/csc1254.html 2 Abstract When we program, we have to deal with errors. Our most basic aim is correctness, but we must deal with

More information

These are notes for the third lecture; if statements and loops.

These are notes for the third lecture; if statements and loops. These are notes for the third lecture; if statements and loops. 1 Yeah, this is going to be the second slide in a lot of lectures. 2 - Dominant language for desktop application development - Most modern

More information

Error Handling in C++

Error Handling in C++ Error Handling in C++ Exceptions, once thrown, must be caught by specialized error-handling code. If an exception goes uncaught, the program will crash to the desktop. Error Handling Many of C++ s built-in

More information

Bruce Merry. IOI Training Dec 2013

Bruce Merry. IOI Training Dec 2013 IOI Training Dec 2013 Outline 1 2 3 Outline 1 2 3 You can check that something is true using assert: #include int main() { assert(1 == 2); } Output: test_assert: test_assert.cpp:4: int main():

More information

Chapter 5 Errors. Bjarne Stroustrup

Chapter 5 Errors. Bjarne Stroustrup Chapter 5 Errors Bjarne Stroustrup www.stroustrup.com/programming Abstract When we program, we have to deal with errors. Our most basic aim is correctness, but we must deal with incomplete problem specifications,

More information

CPSC 427: Object-Oriented Programming

CPSC 427: Object-Oriented Programming CPSC 427: Object-Oriented Programming Michael J. Fischer Lecture 22 November 28, 2016 CPSC 427, Lecture 22 1/43 Exceptions (continued) Code Reuse Linear Containers Ordered Containers Multiple Inheritance

More information

Lecture 14: more class, C++ streams

Lecture 14: more class, C++ streams CIS 330: / / / / (_) / / / / _/_/ / / / / / \/ / /_/ / `/ \/ / / / _/_// / / / / /_ / /_/ / / / / /> < / /_/ / / / / /_/ / / / /_/ / / / / / \ /_/ /_/_/_/ _ \,_/_/ /_/\,_/ \ /_/ \ //_/ /_/ Lecture 14:

More information

Unit 7. 'while' Loops

Unit 7. 'while' Loops 1 Unit 7 'while' Loops 2 Control Structures We need ways of making decisions in our program To repeat code until we want it to stop To only execute certain code if a condition is true To execute one segment

More information

EL2310 Scientific Programming

EL2310 Scientific Programming (pronobis@kth.se) Overview Overview Wrap Up Introduction to Object Oriented Paradigm More on and Members Operator Overloading Last time Intro to C++ Differences between C and C++ Intro to OOP Today Object

More information

G52CPP C++ Programming Lecture 17

G52CPP C++ Programming Lecture 17 G52CPP C++ Programming Lecture 17 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Last Lecture Exceptions How to throw (return) different error values as exceptions And catch the exceptions

More information

1 Introduction to C++ C++ basics, simple IO, and error handling

1 Introduction to C++ C++ basics, simple IO, and error handling 1 Introduction to C++ C++ basics, simple IO, and error handling 1 Preview on the origins of C++ "Hello, World!" programs namespaces to avoid collisions basic textual IO: reading and printing values exception

More information

CS11 Introduction to C++ Fall Lecture 1

CS11 Introduction to C++ Fall Lecture 1 CS11 Introduction to C++ Fall 2006-2007 Lecture 1 Welcome! 8 Lectures (~1 hour) Slides posted on CS11 website http://www.cs.caltech.edu/courses/cs11 7 Lab Assignments on course website Available on Monday

More information

CSCE 206: Structured Programming in C++

CSCE 206: Structured Programming in C++ CSCE 206: Structured Programming in C++ 2017 Spring Exam 2 Monday, March 20, 2017 Total - 100 Points B Instructions: Total of 13 pages, including this cover and the last page. Before starting the exam,

More information

Software Design and Analysis for Engineers

Software Design and Analysis for Engineers Software Design and Analysis for Engineers by Dr. Lesley Shannon Email: lshannon@ensc.sfu.ca Course Website: http://www.ensc.sfu.ca/~lshannon/courses/ensc251 Simon Fraser University Slide Set: 9 Date:

More information

CS242 COMPUTER PROGRAMMING

CS242 COMPUTER PROGRAMMING CS242 COMPUTER PROGRAMMING I.Safa a Alawneh Variables Outline 2 Data Type C++ Built-in Data Types o o o o bool Data Type char Data Type int Data Type Floating-Point Data Types Variable Declaration Initializing

More information

QUIZ. What is wrong with this code that uses default arguments?

QUIZ. What is wrong with this code that uses default arguments? QUIZ What is wrong with this code that uses default arguments? Solution The value of the default argument should be placed in either declaration or definition, not both! QUIZ What is wrong with this code

More information

the gamedesigninitiative at cornell university Lecture 7 C++ Overview

the gamedesigninitiative at cornell university Lecture 7 C++ Overview Lecture 7 Lecture 7 So You Think You Know C++ Most of you are experienced Java programmers Both in 2110 and several upper-level courses If you saw C++, was likely in a systems course Java was based on

More information

EL2310 Scientific Programming

EL2310 Scientific Programming Lecture 14: Object Oriented Programming in C++ (fpokorny@kth.se) Overview Overview Lecture 14: Object Oriented Programming in C++ Wrap Up Introduction to Object Oriented Paradigm Classes More on Classes

More information

QUIZ. What are 3 differences between C and C++ const variables?

QUIZ. What are 3 differences between C and C++ const variables? QUIZ What are 3 differences between C and C++ const variables? Solution QUIZ Source: http://stackoverflow.com/questions/17349387/scope-of-macros-in-c Solution The C/C++ preprocessor substitutes mechanically,

More information

Programming in C++: Assignment Week 8

Programming in C++: Assignment Week 8 Programming in C++: Assignment Week 8 Total Marks : 20 Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology Kharagpur 721302 partha.p.das@gmail.com April 12,

More information

CS11 Introduction to C++ Fall Lecture 6

CS11 Introduction to C++ Fall Lecture 6 CS11 Introduction to C++ Fall 2006-2007 Lecture 6 Today s Topics C++ exceptions Introduction to templates How To Report Errors? C style of error reporting: return values For C Standard Library/UNIX functions,

More information

COMP322 - Introduction to C++ Lecture 10 - Overloading Operators and Exceptions

COMP322 - Introduction to C++ Lecture 10 - Overloading Operators and Exceptions COMP322 - Introduction to C++ Lecture 10 - Overloading Operators and Exceptions Dan Pomerantz School of Computer Science 19 March 2012 Overloading operators in classes It is useful sometimes to define

More information

C++ Programming Lecture 5 Software Engineering Group

C++ Programming Lecture 5 Software Engineering Group C++ Programming Lecture 5 Software Engineering Group Philipp D. Schubert Contents 1. Error handling A. Return codes B. Assertions C. Exceptions 2. Function pointers 3. std::function Error handling How

More information

Introduction to C++ (Extensions to C)

Introduction to C++ (Extensions to C) Introduction to C++ (Extensions to C) C is purely procedural, with no objects, classes or inheritance. C++ is a hybrid of C with OOP! The most significant extensions to C are: much stronger type checking.

More information

int main() { int account = 100; // Pretend we have $100 in our account int withdrawal;

int main() { int account = 100; // Pretend we have $100 in our account int withdrawal; Introduction to Exceptions An exception is an abnormal condition that occurs during the execution of a program. For example, divisions by zero, accessing an invalid array index, or ing to convert a letter

More information

PIC 10A Objects/Classes

PIC 10A Objects/Classes PIC 10A Objects/Classes Ernest Ryu UCLA Mathematics Last edited: November 13, 2017 User-defined types In C++, we can define our own custom types. Object is synonymous to variable, and class is synonymous

More information

Absolute C++ Walter Savitch

Absolute C++ Walter Savitch Absolute C++ sixth edition Walter Savitch Global edition This page intentionally left blank Absolute C++, Global Edition Cover Title Page Copyright Page Preface Acknowledgments Brief Contents Contents

More information

Exceptions. Examples of code which shows the syntax and all that

Exceptions. Examples of code which shows the syntax and all that Exceptions Examples of code which shows the syntax and all that When a method might cause a checked exception So the main difference between checked and unchecked exceptions was that the compiler forces

More information

Fast Introduction to Object Oriented Programming and C++

Fast Introduction to Object Oriented Programming and C++ Fast Introduction to Object Oriented Programming and C++ Daniel G. Aliaga Note: a compilation of slides from Jacques de Wet, Ohio State University, Chad Willwerth, and Daniel Aliaga. Outline Programming

More information

Chapter 15 - C++ As A "Better C"

Chapter 15 - C++ As A Better C Chapter 15 - C++ As A "Better C" Outline 15.1 Introduction 15.2 C++ 15.3 A Simple Program: Adding Two Integers 15.4 C++ Standard Library 15.5 Header Files 15.6 Inline Functions 15.7 References and Reference

More information

Ch. 11: References & the Copy-Constructor. - continued -

Ch. 11: References & the Copy-Constructor. - continued - Ch. 11: References & the Copy-Constructor - continued - const references When a reference is made const, it means that the object it refers cannot be changed through that reference - it may be changed

More information

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by Walter

More information

AN OVERVIEW OF C++ 1

AN OVERVIEW OF C++ 1 AN OVERVIEW OF C++ 1 OBJECTIVES Introduction What is object-oriented programming? Two versions of C++ C++ console I/O C++ comments Classes: A first look Some differences between C and C++ Introducing function

More information

8. The C++ language, 1. Programming and Algorithms II Degree in Bioinformatics Fall 2017

8. The C++ language, 1. Programming and Algorithms II Degree in Bioinformatics Fall 2017 8. The C++ language, 1 Programming and Algorithms II Degree in Bioinformatics Fall 2017 Hello world #include using namespace std; int main() { } cout

More information

C++ Namespaces, Exceptions

C++ Namespaces, Exceptions C++ Namespaces, Exceptions CSci 588: Data Structures, Algorithms and Software Design http://www.cplusplus.com/doc/tutorial/namespaces/ http://www.cplusplus.com/doc/tutorial/exceptions/ http://www.cplusplus.com/doc/tutorial/typecasting/

More information

C++_ MARKS 40 MIN

C++_ MARKS 40 MIN C++_16.9.2018 40 MARKS 40 MIN https://tinyurl.com/ya62ayzs 1) Declaration of a pointer more than once may cause A. Error B. Abort C. Trap D. Null 2Whice is not a correct variable type in C++? A. float

More information

CSE 333 Lecture 9 - intro to C++

CSE 333 Lecture 9 - intro to C++ CSE 333 Lecture 9 - intro to C++ Hal Perkins Department of Computer Science & Engineering University of Washington Administrivia & Agenda Main topic: Intro to C++ But first: Some hints on HW2 Labs: The

More information

COM S 213 PRELIM EXAMINATION #2 April 26, 2001

COM S 213 PRELIM EXAMINATION #2 April 26, 2001 COM S 213 PRELIM EXAMINATION #2 April 26, 2001 Name: Student ID: Please answer all questions in the space(s) provided. Each question is worth 4 points. You may leave when you are finished with the exam.

More information

CS24 Week 3 Lecture 1

CS24 Week 3 Lecture 1 CS24 Week 3 Lecture 1 Kyle Dewey Overview Some minor C++ points ADT Review Object-oriented Programming C++ Classes Constructors Destructors More minor Points (if time) Key Minor Points const Motivation

More information

CS 11 C++ track: lecture 1

CS 11 C++ track: lecture 1 CS 11 C++ track: lecture 1 Administrivia Need a CS cluster account http://www.cs.caltech.edu/cgi-bin/ sysadmin/account_request.cgi Need to know UNIX (Linux) www.its.caltech.edu/its/facilities/labsclusters/

More information

04-24/26 Discussion Notes

04-24/26 Discussion Notes 04-24/26 Discussion Notes PIC 10B Spring 2018 1 When const references should be used and should not be used 1.1 Parameters to constructors We ve already seen code like the following 1 int add10 ( int x

More information

Contents. Error Handling Strategies (cont d) Error handling strategies: error code, assert(), throw-try-catch

Contents. Error Handling Strategies (cont d) Error handling strategies: error code, assert(), throw-try-catch Contents Error handling strategies: error code, assert(), throw-try-catch Exception Handling C++ Object Oriented Programming Pei-yih Ting NTOU CS 28-1 C++waysoferrorhandling Exceptions vs. assert() Error

More information

The pre-processor (cpp for C-Pre-Processor). Treats all # s. 2 The compiler itself (cc1) this one reads text without any #include s

The pre-processor (cpp for C-Pre-Processor). Treats all # s. 2 The compiler itself (cc1) this one reads text without any #include s Session 2 - Classes in C++ Dr Christos Kloukinas City, UoL http://staff.city.ac.uk/c.kloukinas/cpp (slides originally produced by Dr Ross Paterson) A C++ source file may contain: include directives #include

More information

Types, Values, Variables & Assignment. EECS 211 Winter 2018

Types, Values, Variables & Assignment. EECS 211 Winter 2018 Types, Values, Variables & Assignment EECS 211 Winter 2018 2 Road map Strings and string I/O Integers and integer I/O Types and objects * Type safety * Not as in object orientation we ll get to that much

More information

CS11 Intro C++ Spring 2018 Lecture 2

CS11 Intro C++ Spring 2018 Lecture 2 CS11 Intro C++ Spring 2018 Lecture 2 C++ Compilation You type: g++ -Wall -Werror units.cpp convert.cpp -o convert What happens? C++ compilation is a multi-step process: Preprocessing Compilation Linking

More information

G52CPP C++ Programming Lecture 16

G52CPP C++ Programming Lecture 16 G52CPP C++ Programming Lecture 16 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Last Lecture Casting static cast dynamic cast const cast reinterpret cast Implicit type conversion 2 How

More information

Looping and Counting. Lecture 3 Hartmut Kaiser hkaiser/fall_2012/csc1254.html

Looping and Counting. Lecture 3 Hartmut Kaiser  hkaiser/fall_2012/csc1254.html Looping and Counting Lecture 3 Hartmut Kaiser hkaiser@cct.lsu.edu http://www.cct.lsu.edu/ hkaiser/fall_2012/csc1254.html Abstract First we ll discuss types and type safety. Then we will modify the program

More information

Pointers and References

Pointers and References Steven Zeil October 2, 2013 Contents 1 References 2 2 Pointers 8 21 Working with Pointers 8 211 Memory and C++ Programs 11 212 Allocating Data 15 22 Pointers Can Be Dangerous 17 3 The Secret World of Pointers

More information

CS302 - Data Structures using C++

CS302 - Data Structures using C++ CS302 - Data Structures using C++ Pre-Course: Variables, Basic Types, Control Structures Kostas Alexis Slides inspired by the course Modern C++, Uni Bonn: http://www.ipb.uni-bonn.de/teaching/modern-cpp/

More information

Looping and Counting. Lecture 3. Hartmut Kaiser hkaiser/fall_2011/csc1254.html

Looping and Counting. Lecture 3. Hartmut Kaiser  hkaiser/fall_2011/csc1254.html Hartmut Kaiser hkaiser@cct.lsu.edu http://www.cct.lsu.edu/ hkaiser/fall_2011/csc1254.html 2 Abstract First we ll discuss types and type safety. Then we will modify the program we developed last time (Framing

More information

Exceptions, Templates, and the STL

Exceptions, Templates, and the STL Exceptions, Templates, and the STL CSE100 Principles of Programming with C++, Fall 2018 (based off Chapter 16 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/

More information

C++ TEMPLATES. Templates are the foundation of generic programming, which involves writing code in a way that is independent of any particular type.

C++ TEMPLATES. Templates are the foundation of generic programming, which involves writing code in a way that is independent of any particular type. C++ TEMPLATES http://www.tutorialspoint.com/cplusplus/cpp_templates.htm Copyright tutorialspoint.com Templates are the foundation of generic programming, which involves writing code in a way that is independent

More information

III. Classes (Chap. 3)

III. Classes (Chap. 3) III. Classes III-1 III. Classes (Chap. 3) As we have seen, C++ data types can be classified as: Fundamental (or simple or scalar): A data object of one of these types is a single object. int, double, char,

More information

Exceptions, Case Study-Exception handling in C++.

Exceptions, Case Study-Exception handling in C++. PART III: Structuring of Computations- Structuring the computation, Expressions and statements, Conditional execution and iteration, Routines, Style issues: side effects and aliasing, Exceptions, Case

More information

The issues. Programming in C++ Common storage modes. Static storage in C++ Session 8 Memory Management

The issues. Programming in C++ Common storage modes. Static storage in C++ Session 8 Memory Management Session 8 Memory Management The issues Dr Christos Kloukinas City, UoL http://staff.city.ac.uk/c.kloukinas/cpp (slides originally produced by Dr Ross Paterson) Programs manipulate data, which must be stored

More information

Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example

Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example CS 311 Data Structures and Algorithms Lecture Slides Friday, September 11, 2009 continued Glenn G. Chappell

More information

Abstract Data Types (ADTs) 1. Legal Values. Client Code for Rational ADT. ADT Design. CS 247: Software Engineering Principles

Abstract Data Types (ADTs) 1. Legal Values. Client Code for Rational ADT. ADT Design. CS 247: Software Engineering Principles Abstract Data Types (ADTs) CS 247: Software Engineering Principles ADT Design An abstract data type (ADT) is a user-defined type that bundles together: the range of values that variables of that type can

More information

Part X. Advanced C ++

Part X. Advanced C ++ Part X Advanced C ++ topics Philip Blakely (LSC) Advanced C++ 158 / 217 References The following are highly regarded books. They are fairly in-depth, and I haven t read them in their entirity. However,

More information

Operator overloading

Operator overloading 1 Introduction 2 The copy constructor 3 Operator Overloading 4 Eg 1: Adding two vectors 5 The -> operator 6 The this pointer 7 Overloading = 8 Unary operators 9 Overloading for the matrix class 10 The

More information

CSE 333. Lecture 9 - intro to C++ Hal Perkins Department of Computer Science & Engineering University of Washington

CSE 333. Lecture 9 - intro to C++ Hal Perkins Department of Computer Science & Engineering University of Washington CSE 333 Lecture 9 - intro to C++ Hal Perkins Department of Computer Science & Engineering University of Washington Administrivia New exercise posted yesterday afternoon, due Monday morning - Read a directory

More information

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures The main body and cout Agenda 1 Fundamental data types Declarations and definitions Control structures References, pass-by-value vs pass-by-references The main body and cout 2 C++ IS AN OO EXTENSION OF

More information