C++异常处理

    xiaoxiao2021-12-03  51

    #include <exception> class xcp_exception : public std::exception { public: xcp_exception(std::string err = ""): m_err(err) { }     virtual ~xcp_exception() throw() { }     virtual const char* what() const throw() { printf("xcp_exception: %s\n", m_err.c_str()); return m_err.c_str(); } private: std::string m_err; }; int test_execption()  { int nRet = 0; printf("it is test1.\n"); xcp_exception ee("It is test."); throw ee; printf("it is test2.\n"); return nRet; } int main(int argc, char * argv[]) { int nRet = 0; try { nRet = test_execption(); printf("ret of test_execption: %d", nRet); } catch (xcp_exception err) { printf("catch xcp_exception err\n"); err.what(); } catch (xcp_exception &err) { printf("xcp_exception &err\n"); err.what(); } catch (std::exception err) { printf("std::exception err\n"); err.what(); } catch (...) { printf("catch others exception.\n"); } printf("complete to main()\n"); return 0; } 关键事项: (1)函数使用throw进行异常声明(指明只有这些异常产生了才抛出), 也可以不修饰(只要函数内部有异常就抛出) (2)如果一项catch 匹配成功了, 后面的catch 就不会再执行了,除非你再catch中再调用 throw; 重新抛该异常到下面catch检查。 (3)catch后面的语句还会继续执行。 (3)如果抛异常没有catch到,系统会 Aborted (4)每个try块至少跟一个catch,否则系统调用terminate()函数终止程序 (5)抛 xcp_exception 异常, catch 该类型对象 和 该类型引用 效果是一样的。 catch (xcp_exception err) { printf("catch xcp_exception err\n"); err.what(); } catch (xcp_exception &err) { printf("xcp_exception &err\n"); err.what(); } (6) 可以在函数的声明中列出这个函数可能抛掷的所有异常类型。 例如:void fun() throw(A,B,C,D); 若无异常接口声明,则此函数可以抛掷任何类型的异常。 不抛掷任何类型异常的函数声明如下: void fun() throw(); (7)c++标准中有个异常基类, 写自定义异常可以继承它。 也可以不继承它完全独立的类。   class exception    {   public:     exception() throw() { }     virtual ~exception() throw();     /** Returns a C-style character string describing the general cause      *  of the current error.  */     virtual const char* what() const throw();   };

    (8)为了防止异常没有捕获到造成程序 terminate 在catch块最后加上 catch (...) 捕获所有异常 (9)如果异常类型存在父子继承关系, 抛异常子类型对象,catch异常父类型也能捕获到。 (10) 函数内部throw 后, 函数直接退出, 函数内部throw后面的代码不会再执行

    转载请注明原文地址: https://ju.6miu.com/read-679878.html

    最新回复(0)