SlideShare a Scribd company logo
1 of 21
C++ Namespaces,
Exceptions
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
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.
// 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;
}
‘Overlapping’
Namespaces
You can use a similarly
named
field/class/function from
a different namespace
by qualifying it.
// 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;
}
Nested Namespaces
You can also nest your
namespaces (boost
and opencv do this
frequently).
// 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;
}
Aliasing
Namespaces
You can also rename a
namespace.
// using namespace example
#include <iostream>
using namespace std;
namespace first {
double x = 3.1416;
}
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 <iostream>
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 <iostream>
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 <iostream>
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 <iostream>
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
<exception> you can
use the standard
exception class:
// standard exceptions
#include <iostream>
#include <exception>
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:
exception description
bad_alloc thrown by new on allocation failure
bad_cast thrown by dynamic_cast when fails with a referenced type
bad_exception thrown when an exception type doesn't match any catch
bad_typeid thrown by typeid
ios_base::failure 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__);

More Related Content

What's hot

Unit 3 principles of programming language
Unit 3 principles of programming languageUnit 3 principles of programming language
Unit 3 principles of programming language
Vasavi College of Engg
 
Unit 2 Principles of Programming Languages
Unit 2 Principles of Programming LanguagesUnit 2 Principles of Programming Languages
Unit 2 Principles of Programming Languages
Vasavi College of Engg
 

What's hot (20)

C sharp
C sharpC sharp
C sharp
 
Scope rules : local and global variables
Scope rules : local and global variablesScope rules : local and global variables
Scope rules : local and global variables
 
Android share preferences
Android share preferencesAndroid share preferences
Android share preferences
 
C# basics
 C# basics C# basics
C# basics
 
C++ Object Oriented Programming
C++  Object Oriented ProgrammingC++  Object Oriented Programming
C++ Object Oriented Programming
 
Advance Java Topics (J2EE)
Advance Java Topics (J2EE)Advance Java Topics (J2EE)
Advance Java Topics (J2EE)
 
C sharp
C sharpC sharp
C sharp
 
Unit 3 principles of programming language
Unit 3 principles of programming languageUnit 3 principles of programming language
Unit 3 principles of programming language
 
Deep C
Deep CDeep C
Deep C
 
Object-oriented concepts
Object-oriented conceptsObject-oriented concepts
Object-oriented concepts
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT
 
visual basic programming
visual basic programmingvisual basic programming
visual basic programming
 
Java 8 Lambda and Streams
Java 8 Lambda and StreamsJava 8 Lambda and Streams
Java 8 Lambda and Streams
 
C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in Java
 
Java Swing
Java SwingJava Swing
Java Swing
 
Unit 2 Principles of Programming Languages
Unit 2 Principles of Programming LanguagesUnit 2 Principles of Programming Languages
Unit 2 Principles of Programming Languages
 
User defined functions
User defined functionsUser defined functions
User defined functions
 
Introduction to EJB
Introduction to EJBIntroduction to EJB
Introduction to EJB
 
Introduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita GanesanIntroduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita Ganesan
 

Similar to Namespaces

2.overview of c++ ________lecture2
2.overview of c++  ________lecture22.overview of c++  ________lecture2
2.overview of c++ ________lecture2
Warui Maina
 
C++ course start
C++ course startC++ course start
C++ course start
Net3lem
 
Exceptions ref
Exceptions refExceptions ref
Exceptions ref
. .
 
New features and enhancement
New features and enhancementNew features and enhancement
New features and enhancement
Rakesh Madugula
 

Similar to Namespaces (20)

2.overview of c++ ________lecture2
2.overview of c++  ________lecture22.overview of c++  ________lecture2
2.overview of c++ ________lecture2
 
Templates
TemplatesTemplates
Templates
 
6-Exception Handling and Templates.pptx
6-Exception Handling and Templates.pptx6-Exception Handling and Templates.pptx
6-Exception Handling and Templates.pptx
 
C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0
 
Chapter 2
Chapter 2Chapter 2
Chapter 2
 
Unit iii
Unit iiiUnit iii
Unit iii
 
C++ course start
C++ course startC++ course start
C++ course start
 
C Tutorials
C TutorialsC Tutorials
C Tutorials
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Exceptions ref
Exceptions refExceptions ref
Exceptions ref
 
Lecture#6 functions in c++
Lecture#6 functions in c++Lecture#6 functions in c++
Lecture#6 functions in c++
 
Programming in C (part 2)
Programming in C (part 2)Programming in C (part 2)
Programming in C (part 2)
 
Recursion to iteration automation.
Recursion to iteration automation.Recursion to iteration automation.
Recursion to iteration automation.
 
Error and exception in python
Error and exception in pythonError and exception in python
Error and exception in python
 
Summary of C++17 features
Summary of C++17 featuresSummary of C++17 features
Summary of C++17 features
 
C++ L05-Functions
C++ L05-FunctionsC++ L05-Functions
C++ L05-Functions
 
Clean code
Clean codeClean code
Clean code
 
New features and enhancement
New features and enhancementNew features and enhancement
New features and enhancement
 
UNIT III.ppt
UNIT III.pptUNIT III.ppt
UNIT III.ppt
 
UNIT III (2).ppt
UNIT III (2).pptUNIT III (2).ppt
UNIT III (2).ppt
 

More from zindadili (20)

Namespace1
Namespace1Namespace1
Namespace1
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Templates2
Templates2Templates2
Templates2
 
Templates1
Templates1Templates1
Templates1
 
Virtual function
Virtual functionVirtual function
Virtual function
 
Operator overloaing
Operator overloaingOperator overloaing
Operator overloaing
 
Operator overloading2
Operator overloading2Operator overloading2
Operator overloading2
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Function overloading
Function overloadingFunction overloading
Function overloading
 
Aggregation
AggregationAggregation
Aggregation
 
Hierarchical inheritance
Hierarchical inheritanceHierarchical inheritance
Hierarchical inheritance
 
Hybrid inheritance
Hybrid inheritanceHybrid inheritance
Hybrid inheritance
 
Multiple inheritance
Multiple inheritanceMultiple inheritance
Multiple inheritance
 
Abstraction1
Abstraction1Abstraction1
Abstraction1
 
Abstraction
AbstractionAbstraction
Abstraction
 
Access specifier
Access specifierAccess specifier
Access specifier
 
Inheritance
InheritanceInheritance
Inheritance
 
Friend function
Friend functionFriend function
Friend function
 
Enum
EnumEnum
Enum
 

Recently uploaded

Recently uploaded (20)

ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 

Namespaces

  • 2. 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?
  • 3. Namespaces Namespaces are specified similar to a class — in a sense they’re a class with all members static. namespace <name> { <fields / classes / functions> }
  • 4. 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.
  • 5. Using Namespaces 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. // 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; }
  • 6. ‘Overlapping’ Namespaces You can use a similarly named field/class/function from a different namespace by qualifying it. // 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; }
  • 7. Nested Namespaces You can also nest your namespaces (boost and opencv do this frequently). // 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; }
  • 8. Aliasing Namespaces You can also rename a namespace. // using namespace example #include <iostream> using namespace std; namespace first { double x = 3.1416; } namespace second = first; int main () { cout << second::x << endl; return 0; }
  • 9. 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 }
  • 10. 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. }
  • 11. 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 <iostream> using namespace std; int main () { try { throw 20; } catch (int e) { cout << "An error occurred: " << e << endl; } return 0; }
  • 12. 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) { 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; }
  • 13. Exceptions A throw statement immediately exits the function and goes into the catch statements from the function that called it. #include <iostream> 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; }
  • 14. 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 <iostream> 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; }
  • 15. 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"; }
  • 16. 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 ();
  • 17. Standard Exceptions If you #include <exception> you can use the standard exception class: // standard exceptions #include <iostream> #include <exception> 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; }
  • 18. Standard Exceptions There are also default set of exceptions that can be thrown: exception description bad_alloc thrown by new on allocation failure bad_cast thrown by dynamic_cast when fails with a referenced type bad_exception thrown when an exception type doesn't match any catch bad_typeid thrown by typeid ios_base::failure thrown by functions in the iostream library
  • 19. 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; }
  • 20. 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; }
  • 21. 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__);