ios::exceptions()函数

最近在学习OpenGL的时候,在shader保存到本地文件,读取shader文件的时候,碰到了如下形式的函数:

std::ifstream vShaderFile;

vShaderFile.exceptions(std::ifstream::failbit|std::ifstream::badbit);

try
{
    //进行了一系列操作,但没有包含thrwo的函数;
}
catch(std::ifstream::failure e)
{
    std::cout<<"ERROR::SHADER::FILE_NOT_SUCCESFULLY_READ"<<std::endl;
}

由于本人C++功底也不好,以上代码有两点不太明白
1.vShaderFile.exceptions 这个函数是啥?
2.try语句中没有throw语句,catch语句应该去捕获什么异常?

在查阅了c++Reference之后,大致明白。 现在整理如下:
针对第一个问题:什么是exceptions
这是一个ios流的成员函数:std::ios::exceptions。
他有两种重载的形式:

/*get(1)*/  iostate exceptions() const;
/*set(2)*/  void exceptions (iostate except);

根据注释可以很明显的看出,

The first form (1) returns the current exception mask for the stream.

The second form (2) sets a new exception mask for the stream and clears the stream’s error state flags (as if member clear() was called).

1是用来得到当前流的状态的,会返回诸如 goodbit,badbit,eofbit,failbit。
2是用来设置一个新的状态掩码,同时会清除流的状态标志。当流的状态变成所设置的状态的时候,就会抛出一个异常。这也是为什么在try中没有thrwo语句,而catch语句还能正常捕获的原因。
值得注意,流默认设置的状态掩码是 goodbit,所以当流出错的时候,不会主动抛出异常哦。


现在测试如下:
测试1

#include<iostream>
#include<string>

int main()
{
    std::cin.exceptions(std::ios::failbit);//这里只设置了一个failbit的flag
    try
    {
        int test;
        while (std::cin >> test)
            std::cout << test << std::endl;
    }
    catch (std::ios::failure e)
    {
        std::cerr << "Wrong" << std::endl;
        std::cout << std::cin.exceptions() << std::endl;
        std::cout << std::cin.rdstate() << std::endl;
    }
    return 0;
}

测试结果1
可以看到当输入不是int的a的时候,while的条件cin>>test抛出了一个错误,并被catch,
cin.exceptions返回的是2,
cin.rdstate返回的也是2,可以知道抛出以及捕获的过程中,并不会修正这个错误位。

测试2

#include<iostream>
#include<string>

int main()
{
    std::cin.exceptions(std::ios::failbit|std::ios::eofbit);
    try
    {
        int test;
        while (std::cin >> test)
            std::cout << test << std::endl;
    }
    catch (std::ios::failure e)
    {
        std::cerr << "Wrong" << std::endl;
        std::cout << std::cin.exceptions() << std::endl;
        std::cout << std::cin.rdstate() << std::endl;
    }
    return 0;
}

测试2
这次测试数据和上次相同,但多设置了一个eofbit位置。
cin.exceptions返回的是3,和之前的2不同,说明cin.exceptions返回的是设置的异常掩码的状况;
cin.rdstate返回的和上次相同。

可见上述的“同时会清除流的状态标志”的意思是把之前设置的状态标识覆盖掉,改为现在设置的标志。

  • 18
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值