C++ Namespaces, Exceptions CSci 588: Data Structures, Algorithms and Software Design All material not from online sources copyright © Travis Desell, 2011.

Slides:



Advertisements
Similar presentations
Chapter 16 Exception Handling. What is Exception Handling? A method of handling errors that informs the user of the problem and prevents the program from.
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.
1 Chapter 17-2 Templates and Exceptions Dale/Weems.
Exceptions, Templates, And The Standard Template Library (STL) Chapter 16.
1 Handling Exceptions COSC 1567 C++ Programming Lecture 11.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 16 Exception Handling.
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.
CSIS 123A Lecture 11 Exception Handling. Introduction  Typical approach to development:  Write programs assuming things go as planned  Get ‘core’ working.
Copyright © 2012 Pearson Education, Inc. Chapter 16: Exceptions, Templates, and the Standard Template Library (STL)
Monday, Mar 24, 2003Kate Gregory with material from Deitel and Deitel Week 11 Exceptions.
Lesson 16 Exceptions Lesson Exceptions1. Murphy’s Law Anything that can go wrong will go wrong Lesson Exceptions2.
1 CSC241: Object Oriented Programming Lecture No 28.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 16 Exception Handling.
Computer Science 1620 Lifetime & Scope. Variable Lifetime a variable's lifetime is finite Variable creation: memory is allocated to the variable occurs.
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.
CSE333 SECTION 7. Template vs Generics C++ templates are similar to preprocessor macros A template will be “materialized” into multiple copies with T.
Lecture 22 Miscellaneous Topics 4 + Memory Allocation.
CPSC 252 Exception Handling Page 1 Exceptions and exception handling Client programmers can make errors using a class attempting to dequeue an item from.
C++ Exceptions STL Vector. Example int Quotient (int numer, int denom} { if (denom != 0) return (numer/denom); else //What to do?? }
1 CSC241: Object Oriented Programming Lecture No 27.
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.
Variables, Functions & Parameter Passing CSci 588 Fall 2013 All material not from online sources copyright © Travis Desell, 2011.
By Noorez Kassam Welcome to JNI. Why use JNI ? 1. You already have significantly large and tricky code written in another language and you would rather.
Handling Exceptions in java. Exception handling blocks try { body-code } catch (exception-classname variable-name) { handler-code }
Defining New Types Lecture 21 Hartmut Kaiser
C++ Memory Overview 4 major memory segments Key differences from Java
Chapter 8 Scope of variables Name reuse. Scope The region of program code where it is legal to reference (use) a variable The scope of a variable depends.
C ++ Basics by Bindra Shrestha sce.uhcl.edu/shresthab CSCI 3333 Data Structures.
Lecture 3: Getting Started & Input / Output (I/O) “TRON” Copyright 1982 (Walt Disney Productions)
C# Classes and Inheritance CNS 3260 C#.NET Software Development.
1 Announcements Note from admins: Edit.cshrc.solaris instead of.tcshrc Note from admins: Do not use delta.ece.
HANDLING EXCEPTIONS Chapter 9. Outline  Learn about the limitations of traditional error-handling methods  Throw exceptions  Use try blocks  Catch.
CS212: Object Oriented Analysis and Design Lecture 20: Exception Handling-II.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 16: Introduction to C++
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
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 Outline 23.1 Introduction
CS212: Object Oriented Analysis and Design Lecture 19: Exception Handling.
CSCI 383 Object-Oriented Programming & Design Lecture 20 Martin van Bommel.
LECTURE LECTURE 14 Exception Handling Textbook p
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
Input/Output CSci 588: Data Structures, Algorithms and Software Design Fall 2011 All material not from online sources copyright © Travis Desell, 2011
Lecture 12  Namespaces  Exceptions  Type casting  Pre-processor directives.
Java & C++ Comparisons How important are classes and objects?? What mechanisms exist for input and output?? Are references and pointers the same thing??
CMSC 202 Computer Science II for Majors. CMSC 202UMBC Topics Exceptions Exception handling.
CSIS 123A Lecture 7 Static variables, destructors, & namespaces.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Lecture 3: Getting Started & Input / Output (I/O)
C++ Lesson 1.
C ++ MULTIPLE CHOICE QUESTION
IS 0020 Program Design and Software Tools
Exceptions Error Handling and Recovery
Chapter 16 Exception Handling
Exceptions Exceptions are used to signal that an unexpected event has happened in a program C++ will generate exceptions for some errors in the program.
Overview 4 major memory segments Key differences from Java stack
Why exception handling in C++?
EXCEPTION HANDLING.
Object Oriented Programming COP3330 / CGS5409
Learning Objectives What else in C++ Bitwise operator
3.3 Abstract Classes, Assignment, and Casting in a Hierarchy
Overview 4 major memory segments Key differences from Java stack
Exceptions with Functions
Andy Wang Object Oriented Programming in C++ COP 3330
Chapter 17 Templates and Exceptions Part 2
Exceptions 1 CMSC 202.
By Hector M Lugo-Cordero September 3, 2008
CMSC 202 Exceptions.
CMSC 202 Lesson 20 Exceptions 1.
Presentation transcript:

C++ Namespaces, Exceptions CSci 588: Data Structures, Algorithms and Software Design All material not from online sources copyright © Travis Desell, ces/ s/ ng/

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 { }

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

Using Namespaces You can use: using namespace ; 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. // using namespace example #include using namespace std; namespace first { int x = 5; } namespace second { double x = ; } int main () { { using namespace first; cout << x << endl; } { using namespace second; cout << x << endl; } return 0; }

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

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

Aliasing Namespaces You can also rename a namespace. // using namespace example #include using namespace std; namespace first { double x = ; } namespace second = first; 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 occur. #include using namespace std; int main () { try { throw 20; } catch (int e) { cout << "An error occurred: " << e << endl; } return 0; }

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

Exceptions A throw statement immediately exits the function and goes into the catch statements from the function that called it. #include using namespace std; int convert_to_int(char* my_str) throws (int) { 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 If there is no catch statement in a function, it will throw the exception from functions it calls instead of progressing as well. #include using namespace std; int convert_to_int2(char* my_str) throws (int) { throw 30; return 10; } int convert_to_int(char* my_str) throws (int) { int result = 10; result = convert_to_int2(my_str); return result; } 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 You can specify what exceptions a function can throw. //This function can throw an exception of any type. int f0(…); //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 If you #include you can use the standard exception class: // standard exceptions #include using namespace std; 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: exceptiondescription bad_allocthrown by new on allocation failure bad_castthrown by dynamic_cast when fails with a referenced type bad_exceptionthrown when an exception type doesn't match any catch bad_typeidthrown by typeid ios_base::failurethrown 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__);