SNU OOPSLA Lab. Chap8. Namespaces and Exceptions © copyright 2001 SNU OOPSLA Lab.

Slides:



Advertisements
Similar presentations
Chapter 8 Technicalities: Functions, etc. Bjarne Stroustrup
Advertisements

Chapter 6 Writing a Program
Programming Languages and Paradigms
1 Mooly Sagiv and Greta Yorsh School of Computer Science Tel-Aviv University Modern Compiler Design.
C++ Basics Variables, Identifiers, Assignments, Input/Output.
Copyright © 2012 Pearson Education, Inc. Chapter 16: Exceptions, Templates, and the Standard Template Library (STL)
Compilation Encapsulation Or: Why Every Component Should Just Do Its Damn Job.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 6 Functions.
Chapter 11 Separate Compilation and Namespaces Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 12A Separate Compilation and Namespaces For classes this time.
Chapter 3 Data Abstraction: The Walls. © 2005 Pearson Addison-Wesley. All rights reserved3-2 Abstract Data Types Modularity –Keeps the complexity of a.
1 Lab Session-XII CSIT121 Fall 2000 b Namespaces b Will This Program Compile ? b Master of Deceit b Lab Exercise 12-A b First Taste of Classes b Lab Exercise.
Namespaces. Calculator Case-study Consider a simple desk calculator. It can be viewed as being composed of four parts: –The lexer, composing tokens out.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 6: Functions by.
Introduction to C++ Templates and Exceptions l C++ Function Templates l C++ Class Templates l Exception and Exception Handler.
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?? }
 2006 Pearson Education, Inc. All rights reserved Arrays.
©Fraser Hutchinson & Cliff Green C++ Certificate Program C++ Intermediate Namespaces.
Programming Language C++ Xulong Peng CSC415 Programming Languages.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 6 Functions.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
Chapter 6 Writing a Program John Keyser’s Modification of Slides by Bjarne Stroustrup
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Defining New Types Lecture 21 Hartmut Kaiser
CS412/413 Introduction to Compilers and Translators Spring ’99 Lecture 8: Semantic Analysis and Symbol Tables.
1 Compiler Construction (CS-636) Muhammad Bilal Bashir UIIT, Rawalpindi.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
C++ Memory Overview 4 major memory segments Key differences from Java
Slides adapted from: Bjarne Stroustrup, Programming – Principles and Practice using C++ Chapter 6 Writing a Program Hartmut Kaiser
1 CS161 Introduction to Computer Science Topic #9.
Lecture 19 CIS 208 Wednesday, April 06, Welcome to C++ Basic program style and I/O Class Creation Templates.
1 Using Yacc. 2 Introduction Grammar –CFG –Recursive Rules Shift/Reduce Parsing –See Figure 3-2. –LALR(1) –What Yacc Cannot Parse It cannot deal with.
SNU OOPSLA Lab. 9. Source Files and Programs © copyright 2001 SNU OOPSLA Lab.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 6 Functions.
Starting Out with C++ Early Objects ~~ 7 th Edition by Tony Gaddis, Judy Walters, Godfrey Muganda Modified for CMPS 1044 Midwestern State University 6-1.
1 Brief Version of Starting Out with C++, 4th Brief Edition Chapter 6 Functions.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 4 Making Decisions.
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 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a.
SNU OOPSLA Lab. Chap6. Expressions and statements © copyright 2001 SNU OOPSLA Lab.
Chapter 9 Separate Compilation and Namespaces. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Slide 2 Overview Separate Compilation (9.1)
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 12 Separate Compilation and Namespaces.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12 Separate Compilation and Namespaces.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 6: Functions.
1 ENERGY 211 / CME 211 Lecture 7 October 6, 2008.
C++ Namespaces, Exceptions CSci 588: Data Structures, Algorithms and Software Design All material not from online sources copyright © Travis Desell, 2011.
Chapter 6 Functions. 6-2 Topics 6.1 Modular Programming 6.2 Defining and Calling Functions 6.3 Function Prototypes 6.4 Sending Data into a Function 6.5.
A Sample Program #include using namespace std; int main(void) { cout
Chapter 6 Writing a Program Bjarne Stroustrup
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
1 ENERGY 211 / CME 211 Lecture 3 September 26, 2008.
1 Lecture Material Namespaces. 2 There is only one global namespace In programs written by many persons, or using the libraries written by others, there.
C++ Lesson 1.
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Programming with ANSI C ++
Introduction to C++ Systems Programming.
Why exception handling in C++?
Separate Compilation and Namespaces
7 Arrays.
Built-In (a.k.a. Native) Types in C++
Lecture 15 (Notes by P. N. Hilfinger and R. Bodik)
Variables, Identifiers, Assignments, Input/Output
Standard Version of Starting Out with C++, 4th Edition
Presentation transcript:

SNU OOPSLA Lab. Chap8. Namespaces and Exceptions © copyright 2001 SNU OOPSLA Lab.

SNU OOPSLA Lab. C++ Contents Modularization and Interfaces Namespaces Exceptions

SNU OOPSLA Lab. C++ 1. Modularization and Interfaces The desk calculator example(6.1) is composed of five parts The parser, doing syntax analysis The lexer, composing tokens out of characters The symbol table, holding (string,value) pairs The driver, main( ) The error handler

1. Modularization and Interfaces driver parser lexer symbol table error handler “using” just interface

SNU OOPSLA Lab. C++ 1. Modularization and Interfaces When breaking up a program into modules, take care to minimize dependencies between modules

SNU OOPSLA Lab. C++ 2. Namespaces How to represent modules as namespaces A mechanism for expressing logical grouping ex> the declarations of the parser from the desk calculator(6.1) may be placed in a namespace Parser Namespace Parser{ double prim(bool); double term(bool); double expr(bool); } double Parser::prim(bool get){/*…*/} double Parser::term(bool get){/*…*/} double Parser::expr(bool get){/*…*/}

SNU OOPSLA Lab. C++ 2. Namespaces Members of a namespace namespace namespace-name{ //declaration and definitions } or namespace namespace-name{ //declaration } namespace-name::member-name//definition

SNU OOPSLA Lab. C Qualified Names A namespace is a scope, so the usual scope rules hold for namespaces A name from another namespace can be used by the name of its namespace double Parser::term(bool get) //note Parser::qualification {double left = prim(get); //no qualification needed for( ; ; ) switch(Lexer::curr_tok) { //note Lexer::qualification case Lexer::MUL: //note Lexer::qualification left *= prim(true); //no qualification needed }

2.2 Using Declarations The repeated qualification outside its namespace is tedious and distracting=> using-declaration Double Parser::prim(bool get) { if (get) Lexer::get_token(); switch(Lexer::curr_tok){ case Lexer::NUMBER:://… caseLexer::NAME://… //… default: return Error::error (“primary expected”); } Double Parse::prim(bool get) { using Lexer::get_token; using Lexer::curr_tok; using Error::error; if (get) get_token(); switch(curr_tok){ case Lexer::NUMBER:://… //… default: return error(“primary expected”); }

SNU OOPSLA Lab. C Using Directives How to simplify the Parser functions to be exactly our original versions? using-directive Namespace Parser{ double prim(bool); double term(bool); double expr(bool); using namespace Lexer;//make all names from Lexer available using namespace Error;//make all names from Error available } double Parser::term(bool get) {// write Parser’s original functions }

SNU OOPSLA Lab. C Multiple Interfaces namespace Parser{ double expr(bool); } namespace Parser{ double prim(bool); double term(bool); double expr(bool); using Lexer::get_token;//use Lexer’s get_token using Lexer::curr_tok;//use Lexer’s curr_tok using Error::error;//use Error’s error } Interface for users Interface for implementers

SNU OOPSLA Lab. C Multiple Interfaces Driver Parser implementation Parser’Parser Parser’ small interface for users Parser interface for implementers Don’t need to use two separate namespaces

SNU OOPSLA Lab. C Interface Design Alternatives Minimal interface easier to understand, better data hiding properties, easier to modify, compile faster The aim make the set of potential dependencies reduced to the set of actual dependencies

SNU OOPSLA Lab. C Interface Design Alternatives namespace Parser{ //interface for implementers //… double expr(bool); //… } int main() { //… Parser::expr(false); //… } main() depends on Parser::expr()

2.4.1 Interface Design Alternatives namespace Parser{ //interface for implementers //… double expr(bool); //… } namespace Parser_interface{ //interface for users using Parser::expr; } namespace Parser{ //interface for users //… double expr(bool); //… } namespace Parser_interface{ //separately named interface for users using Parser::expr; } Driver Parser implementation Driver Parser implementation Parser_interface Parser Parser_interface Parser’

SNU OOPSLA Lab. C Interface Design Alternatives Minimized dependency namespace Parser_interface{ double expr(bool); } double Parser_interface::expr(bool get) { return Parser::expr(get); } Driver Parser implementation Parser_interface implementation Parser_interfaceParser

SNU OOPSLA Lab. C Avoiding Name Clashes Ex> name clash //my.h: char f(char); int f(int); class String{/* …*/}; //your.h; char f(char); double f(double); class String{/*…*/}; namespace My{ char f(char); int f(int); class String{/* …*/}; } namespace Your{ char f(char); double f(double); class String{/*…*/}; } solution

SNU OOPSLA Lab. C Unnamed Namespaces The namespace without a name How to access members of an unnamed namespace from the outside an unnamed namespace has an implied using-directive namespace{ int a; void f(){/*…*/} int g(){/*…*/} } namespace $$${ int a; void f(){/*…*/} int g(){/*…*/} } using namespace $$$;

SNU OOPSLA Lab. C Name Lookup If a function isn’t found in the context of its use, we look in the namespaces of its arguments This lookup is useful for operator operands and template arguments void f(Chrono::Date d, std::string s) { if(d==s){ //… } else if(d==“august 4, 1914”){ //… } std::operator==() doesn’t take a Date argument, so Chrono::operator==()

SNU OOPSLA Lab. C Namespace Aliases Solution : short alias for a longer namespace name namespace A{…} A::String s1=“Grieg”; A::Strings2=“Nielsen”; namespace American_Telephone_and_Telegraph{…} American_Telephone_and_Telegraph::String s3=“Grieg”; American_Telephone_and_Telegraph::String s4=“Nielsen”; short name, will clash too long namespace ATT=American_Telephone_and_Telegraph; ATT::String s3=“Grieg”; ATT::String s4=“Nielsen”;

SNU OOPSLA Lab. C Namespace Composition Compose an interface out of existing interfaces namespace His_string{ class String{…}; void fill(char); } namespace Her_vector{ template class Vector{…}; } namespace My_lib{ using namespace His_string; using namespace Her_vector; void my_fct(String&); } void f() { My_lib::String s=“Byron”; } using namespace My_lib; void g(Vector & vs) { my_fct(vs[5]); } Only if define something, need to know the real namespace of an entity void My_lib::fill(){…}//error : no fill() declared in My_lib void His_string::fill(){…}//ok:fill() declared in His_string

SNU OOPSLA Lab. C Namespace Composition Ideally a namespace should express a logically coherent set of features not give users access to unrelated features no impose a significant notational burden on users

SNU OOPSLA Lab. C Selection Selection of features from a namespace using-declaration namespace My_string{ using His_string::String; using His_string::operator+; }

SNU OOPSLA Lab. C Composition and Selection namespace His_lib{ class String{…}; template class Vector{…}; } namespace Her_lib{ template class Vector{…}; class String{…}; } namespace My_lib{ using namespace His_lib; using namespace Her_lib; using His_lib::String; using Her_lib::Vector; template class List{…}; } namespace Lib2{ using namespace His_lib; using namespace Her_lib; using His_lib::String; using Her_lib::Vector; typedef Her_lib::String Her_string; template class His_vector :public His_ilb::Vector {…}; template class List{…}; } additional stuff Names explicitly declared in a namespace take priority over names made accessible in another scope by using-directive resolve clash in favor o f His_lib resolve clash in favor o f Her_lib rename “rename” additional stuff

SNU OOPSLA Lab. C Namespaces and C Redesign existing code Make it relatively easy to take a program written without namespaces and turn it into a more explicitly structured one using namespace => using-directive //stdio.h: namespace std{ int printf(const char*…); } using namespace std; //cstdio: namespace std{ int printf(const char*…); } //stdio.h: include using namespace std; for people who don’t want the names implicitly available

SNU OOPSLA Lab. C Namespaces and Overloading Overloading works across namespaces //old A.h: void f(int); //old B.h: void f(char); //old user.c: #include “A.h” #include “B.h” void g() { f(‘a’); //calls the f() from B.h } //new A.h: namespace A{ void f(int); } //new B.h: namespace B{ void f(char); } //new user.c: #include “A.h” #include “B.h” using namespace A; using namespace B; void g() { f(‘a’); //calls the f() from B.h }

SNU OOPSLA Lab. C Namespaces Are Open Can add names to a namespace from several namespace declaration Allows us to present different interfaces to different kinds of users by presenting different parts of a namespace namespace A{ int f();//now A has member f() } namespace A{ int g();//now A has two members, f() and g() }

SNU OOPSLA Lab. C++ 3. Exceptions In module programming, two parts of error handling The reporting of error conditions not resolved locally The handling of errors detected elsewhere Exceptions are C++means of separating error reporting from error handling

SNU OOPSLA Lab. C Throw and Catch The notion of an exception is provided to help deal with error reporting struct Range_error{ int I; Range_error(int ii){I=ii;} }; char to_char(int I) { char c=I&static_cast (-1); if(I!=c) throw Range_error(I); return c; } void h( int I) {try{ char c=to_char(I); } catch(Range_error x){ cerr<<“oops:to_char(“<<x.I<<“)\n”; } exception handlier throw an exception

SNU OOPSLA Lab. C Discrimination of Exceptions Several different possible run-time errors in a program Map into exception with distinct names Ex> 2 error in calculator(6.1) syntax errors attempts to divide by zero try{ expr(false); } catch(Syntax_error) { //handle syntax error } catch(Zero_divide){ //handle divide by zero }

SNU OOPSLA Lab. C Discrimination of Exceptions try{ } catch(input_overflow){ thrown input_overflow(); } Any exceptions thrown while executing a handler must be dealt with by the callers of the try-block Exception handlers can be nested try{ } catch(XXII){ try{ } catch(XXII){ }

SNU OOPSLA Lab. C Exceptions in the Calculator Rework the calculator example(6.1) to separate the handling of errors from the main logic of it The parser eliminate error() detect three syntax errors return error(“divide by 0”); return error(“) expected”); return error(“primary expected”); return error(“divide by 0”); throw Error::Syntax_error(“divide by 0”); throw Error::Syntax_error(“’)’ expected”); throw Error::Syntax_error(“primary expected”); throw Error::Zero_divide();

SNU OOPSLA Lab. C Exceptions in the Calculator The driver handle Zero_divide and Syntax_error int main(int argc, char* argv[]) { while(cin){ try { Lexer::get_token(); //… } catch(Error::Zero_divide){//… skip(); } catch(Error::Syntax_error e){//… skip(); } namespace Driver{ int no_of_errors; std::istream* input; void skip(); } void Driver::skip() { using std::cin; no_of_errors++; while(cin){ //… switch(ch){ case ‘\n’: case ‘;’: cin.get(ch); return; } skip tokens until EOL or ;

Bad for a several reasons: State variables are a common source of confusion and errors Good strategy to keep error handling and “normal” code separate Doing error handling using the same level of abstraction as the code that caused that the error is hazardous To add error-handling code rather than separate error-handing routines int main(int argc, char* argv[]) { bool in_error = false; while (cin){ try{ Lexer::get_token(); //… if (in_error==false) cout<<Parse::expr(false)<<‘\n’; } catch(Error::Zero_divide){ cerr<<“attempt to divide by zero\n”; in_error=ture; } catch(Error::Syntax_error e){ cerr<<“syntax error:”<<e.p<<“\n”; in_error=true; }