开发者

what are the possible exceptions for parsing a config or xml file? [closed]

开发者 https://www.devze.com 2023-03-05 22:01 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. For help clari
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. 开发者_开发问答 Closed 11 years ago.

How do you handle all possible exceptions in parsing a file?

My code has an abstract base class and two derived classes (XML and config) based on type of file I have written code for parsing.


I would just have one exception:

#include <stdexcept>

namespace MyNameSpace
{
    class ParserException: public std::runtime_error
    {
        public:
            ParserException(std::string const& msg)
                : runtime_error(msg)
            {}
    };
};

If there is a problem just throw ParserException with an appropriate error msg. If there is a particular situation where it is easy and conceivable a user would actually recover from then create a specific exception for this situation (derived from ParserException).

  • Do not Create a new exception class for each and every error.
  • If you do create more exceptions for parser. Then derive them from ParserException, so that they can potentially all be handled as a group.
  • If something generic happens. Use one of the standard exceptions.

Usage:

if (bad)
{   throw ParserException("Something Bad Happened");
}


There must be lots of exceptions, many of which may be unlikely to occur, but obvious ones might be:-

  • No data in the file (failed to load for whatever reason)
  • Invalid XML
  • Unexpected format of data (though this should be handled by proper parsing)
  • Illegal characters in XML (not escaped properly)
  • Extended Unicode characters in data (should be handled gracefully in parsing)
  • Parser runs out of memory

That's a start...!

0

精彩评论

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