Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/144.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;try/catch块不捕获给定类型的异常_C++_Exception_Gcc_Ofstream - Fatal编程技术网

C++ C++;try/catch块不捕获给定类型的异常

C++ C++;try/catch块不捕获给定类型的异常,c++,exception,gcc,ofstream,C++,Exception,Gcc,Ofstream,我刚刚遇到了一个例子,在捕获这种类型异常的try块中抛出了类型为std::ios_base::failure的异常,但它没有被捕获 最小工作示例 讨论 这是怎么回事?“terminate”消息明确指定异常的类型是std::ios\u base::failure,因此我看不出它不会被捕获的任何原因 一个有趣的线索是,如果我捕获一个const std::exception&,那么catch块就可以工作,但是如果我捕获一个const std::runtime\u error&(在C++11中,它是st

我刚刚遇到了一个例子,在捕获这种类型异常的
try
块中抛出了类型为
std::ios_base::failure
的异常,但它没有被捕获

最小工作示例 讨论 这是怎么回事?“terminate”消息明确指定异常的类型是
std::ios\u base::failure
,因此我看不出它不会被捕获的任何原因

一个有趣的线索是,如果我捕获一个
const std::exception&
,那么
catch
块就可以工作,但是如果我捕获一个
const std::runtime\u error&
(在C++11中,它是
std::ios\u base::failure的基类,根据)


编辑:我刚刚尝试了
g++
9.2.0,它工作正常。我尝试了几个不同的版本,行为在6.3.0和7.2.0之间发生了变化。我仍然很好奇是否有人知道原因,但看起来它可能与
gcc
本身的错误有关。

1)
std::ofstream
并不是演示问题的最佳方法,因为如果文件不存在,它只会创建它,不会抛出异常。2) 当我将
std::ofstream
更改为
std::ifstream
时,所有内容都被删除。请验证,您的,产生了问题,您声称,它确实产生了问题。究竟是什么导致了错误?该文件存在于当前目录中,但不属于您,或者您删除了对自己文件的写入权限,或者该文件不存在且您在当前目录中没有写入权限?其他?@AlgirdasPreidžius I调用文件
无写访问
是有原因的。它必须是一个我没有写访问权的文件,以便抛出异常。您的Wandbox示例没有再现问题的这一部分。@从技术上讲,
open
失败的原因无关紧要。因为在发生故障时,无论出于何种原因,它都会设置
failbit
。因此,如果尝试使用
ifstream
、使用
open
打开文件,而该文件不存在,则会引发相同的异常。第二个注意事项是,我在中发现了以下条目:“iostreams引发的异常类型,
std::ios_base::failure
,现在使用的是cxx11 ABI。”这意味着什么,以及它与捕获它的能力有何关系?我不知道。但是,有些东西被更改了。@aschepler:
c++filt
有一个
-t
选项来处理这个问题(默认情况下由于错误点击而关闭)。
#include <fstream>
#include <iostream>

int main()
{
    std::ofstream file;
    file.exceptions( std::ofstream::failbit );
    try {
        file.open( "no_write_access" );
    } catch ( const std::ios_base::failure& e ) {
        std::cout << "Look, Ma, I caught an error!" << std::endl;
    }
}
 % g++ --version
g++ (GCC) 6.1.0
Copyright (C) 2016 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

 % g++ main.cpp -std=c++11 -o test && ./test
terminate called after throwing an instance of 'std::ios_base::failure'
  what():  basic_ios::clear
[1]    9734 abort      ./test