C++ 异常

通常异常

如下几篇参考: C++异常处理——经过例子说明。深刻浅出~ C++的异常处理——全面,各个细节基本都说了。不过auto_ptr在C++11中已经被unique_ptr取代了。 错误处理(Error-Handling):为什么、什么时候、如何(rev#2)——已经上升到了至关的高度。 C++处理异常技巧-try,catch,throw,finally——排版太乱,凑合参考一下~ 异常安全,RAII与C++11——很好的文~html

有空看看《exceptional C++》 C++11对异常处理是否有加强还须要了解一下。数组

  1. throw() 改成noexcept了。
  2. unique_ptr 和shared_ptr能够指定deleter替换默认的delete方法来释放资源。如: void end_connection(connection *p) { disconnect(p); } //资源清理函数 unique_ptr<connection, decltype(end_connection)> //资源清理器的“类型” p(&c, end_connection);// 传入函数名,会自动转换为函数指针

能够结合lambda,对付那些C类型须要申请和释放资源的API接口的~:安全

auto fileDeleter = [](FILE* f) { fclose(f); };

std::unique_ptr<FILE, decltype(fileDeleter)> foo(fopen("foo.txt", "w"), fileDeleter);
if (!foo)
    printf("No good\n");
else
    fprintf(foo.get(), "All good\n");

关于除零异常

C++之父在谈C++语言设计的书(The Design and Evolution of C++)里谈到:架构

"low-level events, such as arithmetic overflows and divide by zero, are assumed to be handled by a dedicated lower-level mechanism rather than by exceptions. This enables C++ to match the behaviour of other languages when it comes to arithmetic. It also avoids the problems that occur on heavily pipelined architectures where events such as divide by zero are asynchronous."异步

简单翻译一下: “底层的事件,好比计算上的溢出和除0错,被认为应用有一个一样底层的机制去处理它们,而不是异常。这让C++在涉及到算术领域的性能,能够和其它语言竞争。再者,它也避免了当某些事件,好比除0错是异步的状况下(译者注:好比在别一个线程里发生)所可能形成的‘管道重重’的架构这一问题。”async

因此,提及来,和原生数组访问越界为何不是一异常并没有两样,主要仍是为了“效率/性能”。对于大多数时候的除法操做,咱们会让它出现除数为0的可能性很小,当你认为有这种可能,就本身检查吧,而后本身定义一个除0错的异常。ide

——引自:C++为何抓不到除0错“异常”?函数

除0在Linux下收到的是SIGFPE信号,而非C++的exception。收到SIGFPE,进程直接被kill了。性能

——C++的try/exception不能处理除0异常.net

相关文章
相关标签/搜索