C++ Namespaces, Exceptions

Similar documents
21. Exceptions. Advanced Concepts: // exceptions #include <iostream> using namespace std;

CPSC 427: Object-Oriented Programming

C++ Exception Handling 1

C++ Exception Handling. Dr. Md. Humayun Kabir CSE Department, BUET

! Errors can be dealt with at place error occurs

Homework 4. Any questions?

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

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

Programmazione. Prof. Marco Bertini

IS 0020 Program Design and Software Tools

A Whirlwind Tour of C++

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

Exception Handling in C++

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

C++ PROGRAMMING LANGUAGE: DYNAMIC MEMORY ALLOCATION AND EXCEPTION IN C++. CAAM 519, CHAPTER 15

Programming in C++: Assignment Week 8

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

Programming in C++: Assignment Week 8

CPSC 427: Object-Oriented Programming

Linked List using a Sentinel

PROGRAMMING IN C++ CVIČENÍ

Introduction to Programming

Communication With the Outside World

Laboratorio di Tecnologie dell'informazione

CSC 330 Object-Oriented Programming. Exception Handling CSC 330

ECE 462 Fall 2011, Third Exam

05-01 Discussion Notes

CSCI 104 Exceptions. Mark Redekopp David Kempe

Intermediate Programming, Spring 2017*

Introduction to C++ (Extensions to C)

My First Command-Line Program

More Functions. Pass by Value. Example: Exchange two numbers. Storage Classes. Passing Parameters by Reference. Pass by value and by reference

Object-Oriented Principles and Practice / C++

Exercise 1.1 Hello world

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

CPSC 427: Object-Oriented Programming

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

CSE 333 Lecture smart pointers

Variables. Data Types.

CSE 333. Lecture 10 - references, const, classes. Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington

C++ Programming Fundamentals

CS11 Advanced C++ Fall Lecture 3

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

Exceptions. Why Exception Handling?

Lab 8. Follow along with your TA as they demo GDB. Make sure you understand all of the commands, how and when to use them.

Announcements. CSCI 334: Principles of Programming Languages. Lecture 18: C/C++ Announcements. Announcements. Instructor: Dan Barowy

C++ Constructor Insanity

Exception Handling Pearson Education, Inc. All rights reserved.

CS102 C++ Exception Handling & Namespaces

CPSC 427: Object-Oriented Programming

CS11 Introduction to C++ Fall Lecture 6

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

Introduction to C++ Systems Programming

Module 7 b. -Namespaces -Exceptions handling

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

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

APPENDIX A : KEYWORDS... 2 APPENDIX B : OPERATORS... 3 APPENDIX C : OPERATOR PRECEDENCE... 4 APPENDIX D : ESCAPE SEQUENCES... 5

Chapter 17 - Notes Recursion

Intermediate Programming, Spring 2017*

A Tour of the C++ Programming Language

Dr. Md. Humayun Kabir CSE Department, BUET

2. How many runtime error messages associated with exception? a) 2 b) 4 c) 5 d) infinite

A Tour of the C++ Programming Language

G52CPP C++ Programming Lecture 16

Strings and Stream I/O

GCC : From 2.95 to 3.2

PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics

CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING. Dr. Shady Yehia Elmashad

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings

C++_ MARKS 40 MIN

LAB #8. Last Survey, I promise!!! Please fill out this really quick survey about paired programming and information about your declared major and CS.

Classes, The Rest of the Story

COMP 2355 Introduction to Systems Programming

C++ Scope Resolution Operator ::

Exception Handling Pearson Education, Inc. All rights reserved.

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

CSE 303: Concepts and Tools for Software Development

CSE 333 Lecture smart pointers

CSE 333 Section 9 - pthreads

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

Program template-smart-pointers-again.cc

Homework 5. Yuji Shimojo CMSC 330. Instructor: Prof. Reginald Y. Haseltine

Outline. Zoltán Porkoláb: C++11/14 1

The University of Nottingham

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

Outline. Introduction. Arrays declarations and initialization. Const variables. Character arrays. Static arrays. Examples.

CSE 333 Lecture 9 - intro to C++

MPI 3. CSCI 4850/5850 High-Performance Computing Spring 2018

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces

Overview. C++ Tutorial. Arrays. Pointers. Strings. Parameter Passing. Rob Jagnow

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage:

CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING C ++ Basics Review part 2 Auto pointer, templates, STL algorithms

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

1/29/2011 AUTO POINTER (AUTO_PTR) INTERMEDIATE SOFTWARE DESIGN SPRING delete ptr might not happen memory leak!

POSIX Threads and OpenMP tasks

CSE 333 Lecture smart pointers

CSCI-1200 Data Structures Fall 2017 Lecture 2 STL Strings & Vectors

FROM C TO C++ CRASH COURSE FOR C PROGRAMMERS -PART I- APPLAB

CSC1322 Object-Oriented Programming Concepts

Program template-smart-pointers.cc

Transcription:

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/ All material not from online sources copyright Travis Desell, 2011

Namespaces Namespaces can group classes, objects and functions under a name. This helps prevent code included from multiple sources from conflicting. For example, what if you include code from two separate libraries, each which have a max function or their own implementation of a string class?

Namespaces Namespaces are specified similar to a class in a sense they re a class with all members static. namespace <name> { <fields / classes / functions>

Using Namespaces You ve already used namespaces before, you can either use: using namespace <name>; To use everything within the namespace without having to qualify it (using the :: operator). Or you can specify what namespace something comes from: <name>::<field / class / function> Just like: std::cout << Hello World! << std::endl; Uses cout and endl from the std namespace.

Using Namespaces // using namespace example #include <iostream> using namespace std; namespace first { int x = 5; namespace second { double x = 3.1416; int main () { { using namespace first; cout << x << endl; { using namespace second; cout << x << endl; return 0; You can use: using namespace <name>; Anywhere within your code (it doesn t have to go at the top of the file). This will allow you to use all the fields, classes and functions within that namespace within the scope the using statement was used.

Overlapping Namespaces // using namespace example #include <iostream> using namespace std; namespace first { int x = 5; namespace second { double x = 3.1416; int main () { using namespace first; cout << x << endl; cout << second::x << endl; return 0; You can use a similarly named field/class/ function from a different namespace by qualifying it.

Nested Namespaces // using namespace example #include <iostream> using namespace std; namespace first { namespace second { double x = 3.1416; int main () { cout << first::second::x << endl; return 0; You can also nest your namespaces (boost and opencv do this frequently).

Aliasing Namespaces // using namespace example #include <iostream> using namespace std; namespace first { double x = 3.1416; namespace second = first; You can also rename a namespace. int main () { cout << second::x << endl; return 0;

Exceptions Sometimes problems happen in our programs due to improper input, etc. In the olden days of programming, a common programming style was to have functions return error codes (and have the actual return values be things passed by reference). For example: int convert_to_int(char* my_str, int &my_int) { if (!is_int(my_str)) return 1; //error my_int = converted_value; return 0; //success

Exceptions However, this makes for some messy code, and makes it so code calling the function had to handle any errors: int convert_to_int(char* my_str, int &my_int) { if (!is_int(my_str)) return 1; //error my_str = ; return 0; //success int retval = convert_to_int(something, new_int); if (retval == 1) { //handle error 1 else if (retval == 2) ( // handle error 2 else { //success, we can actually do something.

Exceptions Exceptions provide a better way to handle issues that occur within functions, as well as a way to delegate farther up the call stack any problems that might #include <iostream> using namespace std; int main () { try { throw 20; catch (int e) { cout << "An error occurred: " << e << endl; return 0; occur.

Exceptions You can throw exceptions from within functions. They also can be of any type. #include <iostream> using namespace std; int convert_to_int(char* my_str) throws (int) { if (0 == strcmp(my_str, "")) { throw 30; return 10; int main (int argc, char **argv) { try { convert_to_int(argv[1]); catch (int e) { cout << "An error occurred: " << e << endl; return 0;

Exceptions #include <iostream> using namespace std; A throw statement immediately exits the function and goes into the catch statements from the function that called it. int convert_to_int(char* my_str) throws (int) { if (0 == strcmp(my_str, "")) { throw 30; return 10; int main(int argc, char **argv) { int result = 0; try { result = convert_to_int(argv[0]); catch (int e) { cout << "An error occurred: " << e << endl; //This will print out 0. cout << result is: << result << endl; return 0;

Exceptions #include <iostream> using namespace std; int convert_to_int2(char* my_str) throws (int) { throw 30; If there is no catch return 10; statement in a function, it will throw the exception int convert_to_int(char* my_str) throws (int) { int result = 10; result = convert_to_int2(my_str); from functions it calls return result; instead of progressing as well. int main(int argc, char **argv) { int result = 0; try { result = convert_to_int(argv[0]); catch (int e) { cout << "An error occurred: " << e << endl; //This will print out 0. cout << result is: << result << endl; return 0;

Exceptions You can throw multiple types of exceptions, which can help you determine what kind of error occurred, especially if you ve made classes for your different exception types. If you catch( ) it will be used for any exception not previous specified by the catch blocks before it. class MyException1 { class MyException2 { try { // code here catch (MyException1 e) { cout << exception 1"; catch (MyException2 e) { cout << exception 2"; catch (...) { cout << "default exception";

Exception Specifications //This function can throw an exception of any type. int f0( ); You can specify what exceptions a function can throw. //This function can throw an exception of type int. int f1( ) throws (int); //This function can throw an exception //of type int or char. int f2( ) throws (int, char); //This function cannot throw an exception. int f3( ) throws ();

Standard Exceptions // standard exceptions #include <iostream> #include <exception> using namespace std; If you #include <exception> you can use the standard exception class: class MyException : public exception { virtual const char* what() const throw() { return "My exception happened"; ; int main () { try { throw new MyException(); catch (MyException *e) { cout << e.what() << endl; delete e; return 0;

Standard Exceptions There are also default set of exceptions that can be thrown: exception bad_alloc bad_cast bad_exception bad_typeid ios_base::failure description thrown by new on allocation failure thrown by dynamic_cast when fails with a referenced type thrown when an exception type doesn't match any catch thrown by typeid thrown by functions in the iostream library

Standard Exceptions For example, an exception of type bad_alloc is thrown when there is some problem allocating memory: try { int *myarray = new int[1000]; catch (bad_alloc& e) { cout << "Error allocating memory: << e.what() << endl;

Standard Exceptions All these default exceptions are derived from the standard exception class, so we can catch them using the exception type. Note that when an exception is caught, c++ will go down the catch list and try and match the thrown exception to the type specified. So just like you can assign an instance of a child class to a variable with its parent s type, a child exception will match to its parent s type. try { int *myarray = new int[1000]; catch (exception& e) { cout << Exception: << e.what() << endl;

A Helpful Exception Class The C and C++ give some automatically defined variables, which can be very helpful for making your own exception class: class MyException : public exception { private: int line; char* file; public: MyException(int l, char* f) : line(l), file(f) { virtual const char* what const throw() { ostringstream oss; oss << Exception thrown in file << file << on line << line; return oss.c_str(); throw new MyException( LINE, FILE );