简体   繁体   English

不抛出文件 I/O 异常

[英]File I/O exception doesn't thrown

i have this piece of code that trying to write into a log file.我有这段代码试图写入日志文件。

Logger::Logger(void) //constructor
{
    try{
        log.open("lodg.txt", std::fstream::in); //Open existing file.
        this->writeLog("Logger started", Severity::INFO); //Add line to the log file,
    }catch(fstream::failure e)
    {
        cerr << "File I/O error." << endl;
        cout << e.what() << endl;
    }
}

Now i know that in this case fstream::in will not create a file if it doesn't exist, but the problem is, even though it doesn't create a new file, it doesn't throw any exception, and I'm able to "write" to file that doesn't exist, code like: log << "Write somthing";现在我知道在这种情况下 fstream::in 不会创建一个文件,如果它不存在,但问题是,即使它没有创建一个新文件,它也不会抛出任何异常,而且我'我能够“写入”不存在的文件,代码如下:log << "Write somthing"; //Not throwing any exception. //不抛出任何异常。

By default streams don't throw exceptions (in most situations this is not what you want).默认情况下,流不会抛出异常(在大多数情况下这不是您想要的)。 But you can turn them on.但是你可以打开它们。

// Set the states you want the stream to throw on.
log.exceptions(std::ios::fail | std::ios::bad | std::ios::eof);

Note do this before you open the file so that you throw when you attempt to open.请注意在打开文件之前执行此操作,以便在尝试打开时抛出。


Note: Usually you want to check for failures explicityl.注意:通常你想明确地检查失败。

log.open("File");
if (!log) {
    std::cerr << "Failed to open";
    // throw or fix error.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM