开发者

Do I need to implement a FileNotFoundError exception?

I've a class called TFile, and I can't (don't want to) modify it. It doesn't throw exception if the input/output file is not found but I can check the iternal status using the method IsZombie. Now, I've implemented a very simple exception:

class FileNotFoundError : public std::runtime_error
{
public :

FileNotFoundError(const std::string & file_name="") 
: runtime_error("ca开发者_JAVA百科nnot find file " + file_name), filename(file_name) {}; 
string filename;
~FileNotFoundError() throw() {};
};

and I use it as:

f = new TFile(total.c_str(), "RECREATE") ;
if (f->IsZombie())
{
    throw FileNotFoundError(total);
}

is there a better way to implement this exception, I mean: is it userful to throw a standard exception as ifstream::failure instead of my custom exception?


There is no std exception that gives you a highly selective way to catch a 'file not found' error condition. So, yes, if you want to signal that condition with an exception and you want to allow the client code to do something meaningful then you need to create your own class for that.

There is however also a reason why that exception doesn't already exist, even though it is by far the most common mishap. It's kinda normal that a file isn't there when you expect it to be. Your program is not in control of the file system. Or maybe the user typed the file name wrong, something like that. It isn't really exceptional that this goes wrong. Don't use exceptions for non-exceptional cases.

This is a mixed message. Do use it when the client code had a reasonable way to check for itself that the file should exist and continuing program execution without that resource is unlikely.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜