cout可以抛出异常吗? [英] Can cout throw an exception?

查看:151
本文介绍了cout可以抛出异常吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

If the operation sets an internal state flag that was registered with
member exceptions, the function throws an exception of member type failure.


在我看来,cout可以抛出一个例外。这是真的?

This indicates to me that cout can throw an exception. Is this true? What kind of scenario could force this?

推荐答案

是的,但是实际上没有人调用 cout.exceptions( iostate)来启用它。

Yes, but practically nobody ever calls cout.exceptions(iostate) to enable that.

编辑以阐明:

std :: ios_base 是一个抽象类,为所有流提供基本的实用程序功能。 std :: ios_base< CharT,Traits> 是其抽象子类,添加了更多实用程序功能。

std::ios_base is an abstract class that provides basic utility functions for all streams. std::ios_base<CharT, Traits> is an abstract subclass thereof, adding more utility functions.

std :: ios_base :: iostate 是位掩码类型,由以下位组成,可能是 ed:

std::ios_base::iostate is a bitmask type, consisting of the following bits, with may be ored:

badbit (used for weird underlying errors)
eofbit (used after you hit EOF)
failbit (the normal error for badly-formatted input)

另外, iostate :: goodbit 等效于 iostate()(基本上为0)。

Additionally, iostate::goodbit is equivalent to iostate() (basically a 0).

通常,当您执行I / O,在每次输入操作之后,检查流的布尔值以查看是否发生错误,例如 if(cin>&val;){cout<< val; } ...对于输出,可以简单地发出一堆并仅在最后检查成功(对于cout,则完全不检查)是可以的。

Normally, when you perform I/O, you check the boolean value of the stream to see if an error occurred, after every input operation, e.g. if (cin >> val) { cout << val; } ... for output, it's okay to simply emit a bunch and only check success at the end (or for cout, to not check at all).

但是,有些人更喜欢例外,因此可以将每个流配置为将某些返回值转换为例外:

However, some people prefer exceptions, so each individual stream can be configured to turn some of those return values into exceptions:

std::ios_base::iostate exceptions() const;
void exceptions(std::ios_base::iostate except);

在C ++中很少这样做,因为我们不会盲目地崇拜像某些其他语言的依附者这样的例外。特别是, I / O出了点问题是通常案例,因此扭曲控制流没有任何意义。

This is rarely done in C++, since we don't mindlessly worship exceptions like adherents of some other languages. In particular, "something went wrong with I/O" is a usual case, so it doesn't make sense to contort control flow.

示例:

$ cat cout.cpp
#include <iostream>

int main()
{
    std::cout.exceptions(std::cout.badbit);

    std::cout << "error if written to a pipe" << std::endl;
}
$ sh -c 'trap "" PIPE; ./cout | true'
vvv 2018-06-21 23:33:13-0700
terminate called after throwing an instance of 'std::ios_base::failure[abi:cxx11]'
  what():  basic_ios::clear: iostream error
Aborted

(请注意,在Unix系统上,您必须忽略SIGPIPE才能使程序甚至有机会来处理此类错误,因为对于许多程序而言,简单地退出是正确的做法-这通常允许 head 上班)

(Note that, on Unix systems, you have to ignore SIGPIPE in order for the program to even have a chance to handle such errors, since for many programs, simply exiting is the right thing to do - this is generally what allows head to work)

这篇关于cout可以抛出异常吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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