1

I'm writing a Python-based parser that can understand some configuration files that we use. The files will basically consist of (name, type) and (name, value) pairs:

Parameter file:

# defines a field called some_bool of type boolean
some_bool : bool

Config file:

# assigns True to some_bool
some_bool = bool

I'm not sure what to do when I encounter a syntax error inside a file I am parsing:

# bol instead of bool
some_bool : bol

Is it bad form to raise a SyntaxError exception in that case or are SyntaxError exceptions better left to show problems in Python code?

2
  • using SyntaxError might be confusing. Either I'd create some special exception type called eg. ParseError or ignore given value and just log in as a warning. Commented Jun 4, 2014 at 13:27
  • 1
    @yedpodtrzitko Great idea! I did implemented it like you suggested. Post this as an answer so I can accept it. Commented Jun 4, 2014 at 15:30

2 Answers 2

1

using SyntaxError might be confusing. Either I'd create some special exception type called eg. ParseError or ignore given value and just log in as a warning

Sign up to request clarification or add additional context in comments.

Comments

1

SyntaxError may be confusing, but I require further argumentation before I am persuaded that this is a good reason not to use it in these cases. IMO it's equally or more confusing to use a different kind of exception.

Even if it might be confusing about when parsing (e.g.) domain-specific code, surely we can -in the error message- make it unambiguous that it is the domain-specific language that has the error, rather than the Python source.

In addition, a SyntaxError offers ready-made fields for line number and filename. Rolling your own SyntaxError would require reinventing those wheels.

The accepted answer here says

Use the most specific Exception constructor that semantically fits your issue.

... and an error encountered while parsing is (semantically) a SyntaxError.

My gut feeling is that an unambiguously constructed SyntaxError is the right thing in such cases. It's also the accepted answer here.

Can anyone convince me otherwise?

1 Comment

SyntaxError sometimes changes the message on it's own, for example if the line with bad syntax is print 'test', instead of sending the given message, Python will complain about missing parentheses. To avoid this, you must raise a custom exception that extends SyntaxError. You won't get the message then.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.