25

I'm writing a parser for a certain file format. If a file is not correctly formatted (and can not be parsed) then the parser throws an exception.

What exception class, in the Python 2 exception hierarchy, should I use?

Johan Råde
  • 20,480
  • 21
  • 73
  • 110
  • 1
    See also the section on [user-defined exceptions](http://docs.python.org/tutorial/errors.html#user-defined-exceptions) in the Python tutorial. – Sven Marnach Feb 14 '12 at 15:37
  • @Sven Marnach: The parser is part of an extension module written using Boost.Python. And I have no idea how to derive new exception classes using the Python C-API or Boost.Python. Therefore I prefer to use one of the existing exception classes. Possible candidates seem to be Exception, ValueError and IOError. – Johan Råde Feb 14 '12 at 15:58
  • See http://stackoverflow.com/questions/2261858/boostpython-export-custom-exception. If your actual problem is how to create a custom exception class with boost.python, you have asked the wrong question. :) – Sven Marnach Feb 14 '12 at 16:05
  • See also http://stackoverflow.com/questions/9620268/boost-python-custom-exception-class – Johan Råde Mar 13 '12 at 19:26

2 Answers2

17

ValueError seems to be appropriate.

Jakub Roztocil
  • 15,930
  • 5
  • 50
  • 52
13

How about

class XyzParseError(Exception):
    pass

where XyzParser is the name of your parser class? That's also what HTMLParser in the standard library does.

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
  • 1
    Why should I derive from Exception instead of ValueError (as suggested by jkbr)? – Johan Råde Feb 14 '12 at 12:46
  • 2
    @user763305: jkbr did not suggest to *derive* from `ValueError`, but to use `ValueError` itself. You should derive from `Exception` because people writing `except ValueError` most certainly don't want to catch `XyzParseError`. – Sven Marnach Feb 14 '12 at 13:22
  • there are too many good and ready to use exception classes, no need for XyzParseError – Sławomir Lenart Jun 15 '17 at 18:37
  • @ups When catching exceptions, you want to be able to be as specific as possible. Catching unwanted exceptions hides errors and leads to hard-to-debug bugs. So if you reuse `ValueError` here and catch this instead of a custom exception, you risk catching exceptions that you did not intend to catch. – Sven Marnach Jun 15 '17 at 18:48