class Book {
public:
Book(const std::string& str) try:ISDN(str) {//知识点
if (str.empty())
throw std::runtime_error("ISDN is empty");
}
catch (std::runtime_error& e) {
std::cout << e.what() << std::endl;
}
std::string ISDN;
void print() {
std::cout << "The ISDN is: " << ISDN << std::endl;
}
};
void exception_example(){
try {// 多层
try {
Book b1("0012021");
Book b2("9900");
if (b1.ISDN != b2.ISDN)
throw;// 该层不处理,交由上一层处理
}
catch (std::runtime_error& e) {
std::cout << e.what() << std::endl;
}
}
catch (std::logic_error& e) {//括号必须添加
std::cout << e.what() << std::endl;
}
}
void auto_ptr_example() {//异常安全机制
std::auto_ptr<Book> ptr(new Book("08991"));
ptr->print();
}
void copy_operation_example() {
std::auto_ptr<Book> ptr(new Book("08991"));
std::auto_ptr<Book> cpyPtr(ptr);
//ptr->print(); //error, 破坏性复制
//if (ptr) //error
if (ptr.get()==0)// 通过get判断指针是否为空
ptr.reset(new Book("08992"));
ptr->print();
}
// 空说明表指出函数不抛出异常
void exception_specification_example1() throw() {
}
void exception_specification_example2() throw(std::runtime_error) {
throw std::runtime_error(" exception_specification_example2");
}
异常类型:
资料:点击打开链接