c++ primer 第十八章习题
练习18.1 (a) range_error (b range_error 会抛出临时对象指针
练习18.2 会销毁函数中创造的对象,其中指针p会导致内存泄漏
练习18.3 可以把指针p使用智能指针或者封装成有析构函数的类
练习18.4 调换顺序即可
练习18.5 try {... }catch(exception e) { cout << e.what()<<endl;}
练习18.6 (a throw new exceptionType();
(b throw exception();
(c throw 1;
练习18.9
class isbn_mismatch: public std::logic_error {
public:
explicit isbn_mismatch(const std::string &s): std::logic_error(s) {}
isbn_mismatch(const std::string& s, const std::string &lhs, const std::string& rhs):
std::logic_error(s),left(lhs),right(rhs) {}
const std::string left, right;
};
Sales_data&
Sales_data::operator+=(const Sales_data& rhs) {
if(isbn() != rhs.isbn())
throw isbn_mismatch("wrong isbn",isbn(),rhs.isbn());
units_sold += rhs.units_sold;
revenue += rhs.revenue;
return *this;
}
练习18.10
不抛出异常会terminate
练习18.11
在catch里处理异常时候使用what,再抛出异常可能无法处理,而