C++异常处理
C异常处理错误明显的比如代码不规范编译错误、头文件引用错误、文件编码错误异常程序运行之后由内存、硬盘、操作系统、网络出现的意外。C语言怎么处理断言assert判断指针不为空。条件不成立则abort终止程序assert ! NULL;返回errno错误号errno.hdup复制文件描述符返回最小可用的新 fddup2强制复制到指定的新 fd常用作重定向int fp open(a.txt,O_RDONLY); 打开文件返回文件描述符fd失败返回-1if (fp2){perror(open);} 打开文件错误信息int fp open(a.txt,O_RDONLY); 打开文件返回文件描述符fd失败返回-1if (fp2){char * err strerr(errno);} 显示错误信息string.h错误日志文件int efd open(error.log); ----stderr文件号2dup2(efd,2);C异常机制简述异常机制尝试捕获异常并处理。 ---- try{...}catch(异常类型 对象名){...}通过判断的方式抛出异常编写步骤throw抛出异常语法throw 变量/对象/数据变量的数据类型 ----任意类型或类对象的类型 ----任意类型或类try尝试捕获语法try{可能存在异常的语句; }catch捕获并处理异常语法catch异常类型 对象/变量{处理异常语句; }异常被处理之后则不会向上抛出void show(char* s) { //assert(s ! NULL); if (s NULL)throw空指针异常; s[0] a; cout sendl; } int main() { cout --test error-- endl; try {//尝试捕获异常 //show(const_castchar*(hi,disen!)); char* info new char[32] {good,disen!}; show(info); show(nullptr); } catch(const char* err){ cerr err endl;//错误输出 } }异常处理中的栈捕获栈对象的解旋抛出异常对象时临时对象存储到异常栈中。抛出异常对象是局部对象时则执行拷贝构造在异常栈中。捕获到异常对象从异常栈中查找到了。如果是以非引用的方式则会从异常栈中拷贝过来异常处理完场之后则会释放对象空间。如果是以引用方式引用的是栈中的异常对象不会拷贝。设计异常类的建议具有派生体系时 基类引用的捕获放在最后面。class BaseException { private: string msg; public: BaseException(const string msg) :msg(msg) {} virtual string error() { return msg; } }; class DivByZeroException :public BaseException { public: DivByZeroException():BaseException(除数为0){} }; class NullPointException :public BaseException { public: NullPointException() :BaseException(空指针) {} }; class TimeoutException : public BaseException { private: int timeout; public: TimeoutException(int timeout) : BaseException(连接超时:), timeout(timeout) {} string error()override { char buf[128] ; sprintf_s(buf, %s %d, BaseException::error().c_str(), timeout); return string(buf); } }; void test1() { cout test1 throw NullPointExcepyion endl; throw NullPointException(); } void test2() { cout test2 throw TimeoutException endl; throw TimeoutException(100); } void test3() { cout test3 throw DivByZeroException endl; throw DivByZeroException(); } int main() { try { //test2(); test3(); } catch (NullPointException e) {//异常类的基类引用体现多态性 cout NullPointException: e.error() endl; } catch (TimeoutException e) {//异常类的基类引用体现多态性 cout TimeoutException: e.error() endl; } catch (BaseException e) {//异常类的基类引用体现多态性 cout BaseException: e.error() endl; } return 0; }C异常体系C 异常是树形继承体系所有异常的最终基类只有一个std::exception整个体系分为两大分支逻辑错误代码写错、参数错、前提不满足程序可避免运行时错误 运行时环境问题、外部资源失败程序无法避免bad_allocnew 分配内存失败bad_castdynamic_cast 转换失败bad_typeidtypeid 空指针bad_exception异常抛出异常C11中的noexcept关键字noexcept告诉编译器这个函数绝对不会抛异常。如果函数声明了 noexcept内部却 throw 了程序会直接终止不会进入 catch直接崩溃。最佳应用位置1.构造函数2.拷贝构造3.getter相关的成员函数void test3(int v) noexcept{ //runtime_error运行时异常 //bad_exception错误的 if (v -1)throw out_of_range(v下标越界); }