#include <exception>
#include <string>
#include <typeinfo>
#include <iostream>
// Class declarations
class BaseExc {
public:
explicit BaseExc();
virtual ~BaseExc() {};
protected:
BaseExc(const std::string& type);
private:
std::string _id;
};
class IOExc: public BaseExc {
public:
explicit IOExc();
};
//Class method declarations
BaseExc::BaseExc():_id(typeid(this).name()) {
}
BaseExc::BaseExc(const std::string& type): _id(type) {
}
IOExc::IOExc(): BaseExc(typeid(this).name()) {
}
int input(void);
int main(void) {
int rnd = input();
try {
if (rnd==0) {
throw IOExc();
} else {
throw BaseExc();
}
}
catch(BaseExc exc) {
std::cout << "Intercept BaseExc" << std::endl;
}
return 0;
}In this example, the catch statement takes
a BaseExc object by value. Catching exceptions
by value causes copying of the object. The copying can cause:
Correction — Catch Exceptions by ReferenceOne possible correction is to catch exceptions by reference.
#include <exception>
#include <string>
#include <typeinfo>
#include <iostream>
// Class declarations
class BaseExc {
public:
explicit BaseExc();
virtual ~BaseExc() {};
protected:
BaseExc(const std::string& type);
private:
std::string _id;
};
class IOExc: public BaseExc {
public:
explicit IOExc();
};
//Class method declarations
BaseExc::BaseExc():_id(typeid(this).name()) {
}
BaseExc::BaseExc(const std::string& type): _id(type) {
}
IOExc::IOExc(): BaseExc(typeid(this).name()) {
}
int input(void);
int main(void) {
int rnd = input();
try {
if (rnd==0) {
throw IOExc();
} else {
throw BaseExc();
}
}
catch(BaseExc& exc) {
std::cout << "Intercept BaseExc" << std::endl;
}
return 0;
}