C++_Primer chapter17 1.异常处理

来源:互联网 发布:大数据时代的喜与忧 编辑:程序博客网 时间:2024/06/05 03:49
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) //errorif (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");}

异常类型:


资料:点击打开链接

0 0
原创粉丝点击