Raising SyntaxError inside a Python

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?


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


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 (eg) 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?

链接地址: http://www.djcxy.com/p/25870.html

上一篇: 在Ruby on Rails中调用外部API时如何处理错误/异常?

下一篇: 在Python中引发SyntaxError