[Python-ideas] why not try without except?

Andre Engels andreengels at gmail.com
Sat Apr 25 10:58:53 CEST 2009


On Sat, Apr 25, 2009 at 10:32 AM, spir <denis.spir at free.fr> wrote:
> Hello,
>
> In various cases, we need to do something (set or update a var or attribute, launch an action, compute data), or not, according to a condition that is a potential case of exception.
> Python provides the try...except construct to allow straightforward expression of the non-exceptional case without overloading the code with explicit checkings.
>
> Still, in the common case above, the result is
>   try:
>      <do_something>
>   except ErrorType:
>      pass
> or we have to fall back to a pre-checking construct
>   if not <error_case>:
>      <do_something>
>
> For instance
>   try:
>      text += doc.footer
>   except ErrorType:
>      pass
> or
>   if hasattr(doc, 'footer')
>      text += doc.footer
>
>
> Actually, this shows that 'try' alone can be considered analog to 'if' without 'else' clause, needed when the condition may raise an exception. Both express an optional action. This could be written more directly, because we do not need the condition:
>   ? <do_something>
>   option <do_something>
> with the meaning: "Try & do this, but if there's an exception just let it down."
>
> The same syntax may be reused in other contexts such as for having optional parameters:
>   def f(data, option param):
>   def f(data, ? param):
> Actually, the meaning is the same: "Try & and read a second argument, but if you step on an exception just let it down." Moreover, the body of the func will probably use precisely the same construct to try and do something using the optional param, e.g.:
>   class Circle:
>      .......
>      def draw(self, ? fill_color):
>         <draw outline>
>         ? self.fill(fill_color)
>
> As a nice side-effect, this would also remove one of the common (mis?)uses of None -- which is often considered problematic because of conflicting various uses.
>
> I would then support the introduction of such a syntax, or of 'try' without 'except'. And sincerally thank you for explaining why the latter was not allowed from start.

-1 for making bad programming easier, but not good programming. One
should only ignore exceptions if one is 100% sure why an error
occured, if not, the fact that an error occured should somehow be
noted.

That is, try without except would be equivalent to the following bad
programming:

try:
    do_something
except:
    pass

Good programming would be either:

try:
    do_something
except some_specific_error:
    pass

or

try:
    do_something
except:
    notify_that_error_occurred

neither of which would be made easier by try-without-except.

-- 
André Engels, andreengels at gmail.com



More information about the Python-ideas mailing list