[Tutor] Inherit from SyntaxError?

Mats Wichmann mats at wichmann.us
Tue Mar 21 14:09:04 EDT 2023


On 3/21/23 11:07, Albert-Jan Roskam wrote:
>     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?

KeyboardInterrupt and SystemExit are a little tricky, though the way 
they're set up should cause few problems (they don't inherit from 
Exception, as you normally want to handle them separately and not catch 
them in a general catch of Exception).

MemoryError, *in theory* is raised if there's a chance of recovery. But 
there are situations, I presume, where external forces might get you - 
the operating system decides to kill Python.



More information about the Tutor mailing list