为什么C ++ STL iostream不是“异常友好”? [英] Why are C++ STL iostreams not "exception friendly"?

查看:208
本文介绍了为什么C ++ STL iostream不是“异常友好”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我习惯了Delphi VCL框架,其中TStreams引发异常,例如找不到文件,磁盘已满。我正在移植一些代码来使用C ++ STL,并且被iostreams抓住,默认情况下不会抛出异常,而是设置 badbit / failbit flags

I'm used to the Delphi VCL Framework, where TStreams throw exceptions on errors (e.g file not found, disk full). I'm porting some code to use C++ STL instead, and have been caught out by iostreams NOT throwing exceptions by default, but setting badbit/failbit flags instead.

两个问题...

a:为什么 - 对于第一天的例外情况,似乎是一种奇怪的设计决定?

a: Why is this - It seems an odd design decision for a language built with exceptions in it from day one?

b:最好避免这种情况?我可以产生像我所期望的那样抛出垫片,但是这样的感觉就像重塑轮子。也许有一个BOOST库可以更清晰地执行此操作?

b: How best to avoid this? I could produce shim classes that throw as I would expect, but this feels like reinventing the wheel. Maybe there's a BOOST library that does this in a saner fashion?

推荐答案

a。 t从第一天开始例外。 C与课程始于1979年,1989年增加了例外。同时, stream library早在1984年就被写成(后来成为 iostreams 在1989年(后来在1991年由GNU重新实现)),它一开始就不能使用异常处理。

a. C++ isn't built with exceptions from day one. "C with classes" started in 1979, and exceptions were added in 1989. Meanwhile, the streams library was written as early as 1984 (later becomes iostreams in 1989 (later reimplemented by GNU in 1991)), it just cannot use exception handling in the beginning.

参考:

  • Bjarne Stroustrup, A History of C++: 1979−1991
  • C++ Libraries

b。可以通过 .exceptions 启用异常code>方法

b. You can enable exceptions with the .exceptions method.

// ios::exceptions
#include <iostream>
#include <fstream>
#include <string>

int main () {
  std::ifstream file;
  file.exceptions ( ifstream::failbit | ifstream::badbit );
  try {
    file.open ("test.txt");
    std::string buf;
    while (std::getline(file, buf))
      std::cout << "Read> " << buf << "\n";
  }
  catch (ifstream::failure e) {
    std::cout << "Exception opening/reading file\n";
  }
  std::cout.flush();

  file.close();

  return 0;
}

这篇关于为什么C ++ STL iostream不是“异常友好”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆