[Tutor] Inherit from SyntaxError?
Albert-Jan Roskam
sjeik_appie at hotmail.com
Tue Mar 21 13:07:19 EDT 2023
On Mar 19, 2023 23:06, Cameron Simpson <cs at cskk.id.au> wrote:
On 19Mar2023 10:30, Albert-Jan Roskam <sjeik_appie at hotmail.com> wrote:
> I'm writing a parser using Beazly's PLY package. I defined a custom
> exception (actually, two: one for the lexer and one for the parser).
They
> inherit from SyntaxError. Along with a few other exceptions (e.g.
> MemoryError), I've always regarded SyntaxError as "special". Are
there any
> disadvantages to inheriting from SyntaxError? I could also inherit
from
> ValueError.
Sounds good to me. I've got a class which inherits from SyntaxError:
class ParseError(SyntaxError):
''' A ParseError subclasses SyntaxError in order to change the
initialiser.
This object has an additional attribute .context for the
relevant FileContext
(which has a .parent attribute).
'''
def __init__(self, context, offset, message, *a):
''' Initialise a ParseError given a FileContext and the offset
into `context.text`.
Accept optional arguments `*a` after the `message`; if
supplied these
are embedded into `message` with %-formatting.
'''
if a:
message = message % a
self.msg = message
self.filename = context.filename
self.lineno = context.lineno
self.text = context.text
self.offset = offset
self.context = context
I've had no problems, and it seems entirely sensible.
======
Hi Alan, Cameron,
Thanks! I now created one BaseParserError (inherits from SyntaxError) and
a lexer + parser error (they each inherit from BaseParserError).
So, is MemoryError the only really tricky exception? I mean, the
interpreter might just die before it is able to recover from the
MemoryError?
Best wishes,
Albert-Jan
More information about the Tutor
mailing list