PEP 317: Eliminate Implicit Exception Instantiation

Evan Simpson evan at 4-am.com
Mon Jun 9 19:13:04 CEST 2003


Steven Taschuk wrote:
> Eliminating these forms of ``raise`` makes it impossible to use string
> exceptions; accordingly, this PEP also proposes the formal deprecation
> and eventual elimination of string exceptions.

Rather than eliminating string exceptions, I suggest a new (ab)use and 
semantics for them, based on my old "break '<string>', continue 
'<string>'" proposal:

1. At compile time, require "raise '<string>'" to be lexically enclosed 
by a matching "try: ... except '<string>':".

2. Treat such combinations as though they were a goto/label pair.  In 
other words, rather than invoking the exception machinery, compile the 
"raise" into a jump bytecode.

This would allow for labelled exits from a block of code.  Note that 
"raise 'foo'" without a matching "except 'foo':' is a SyntaxError, so 
this is a very localized, tame goto, and typos in the strings are highly 
likely to be caught at compile-time.

Abstracted Example:

   try:
       m = re.search(<first pattern>)
       if m:
           if <expression involving m>:
               raise 'First case'
           if <expression involving m>:
               raise 'Second case'
       m = re.search(<second pattern>)
       if m:
           if <expression involving m>:
               raise 'First case'
           if <expression involving m>:
               raise 'Second case'
       if <some other test>:
           raise 'Second case'
       return
   except 'First case':
       <handle the first case>
   except 'Second case':
       <handle the second case>
   <code common to both cases>

I've both written and encountered code that has this sort of logical 
structure, but which had to be written as some variation on:

   case = None
   m = re.search(<first pattern>)
   if m:
       if <expression involving m>:
           case = 1
       elif <expression involving m>:
           case = 2
   if case is None:
       m = re.search(<second pattern>)
       if m:
           if <expression involving m>:
               case = 1
           elif <expression involving m>:
               case = 2
   if case is None and <some other test>:
       case = 2
   if case is None:
       return
   if case == 1:
       <handle the first case>
   else:
       <handle the second case>
   <code common to both cases>

Cheers,

Evan @ 4-am







More information about the Python-list mailing list