# Enhanced try() function

**URL:** <https://discuss.python.org/t/enhanced-try-function/8313>\
**Category:** Ideas\
**Created:** [April 20, 2021, 7:47am UTC](https://discuss.python.org/t/enhanced-try-function/8313 "2021-04-20T07:47:23Z")\
**Posts on this page:** 12\
**Page:** 1

<div class="post-metadata">

**Author:** ![edusanketdk](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/edusanketdk/32/3986_2.png) [@edusanketdk](https://discuss.python.org/u/edusanketdk)\
**Post date:** [April 20, 2021, 7:47am UTC](https://discuss.python.org/t/enhanced-try-function/8313/1 "2021-04-20T07:47:23Z")

</div>

Consider this code:

```
try:
    # potential erroneous statement
    # other statements dependable on the above statement
except:
    pass

```

Meaning, I have a statement that may cause error and next statements should execute only if no error occurs. However, I don’t need some statements that will execute if an error occurs. In this case, I have to put a simple pass statement in the exception block.

A lot of times this case is encountered and I think the two unnecessary except block statements can be eliminated by adding the following try function to the core module.

```
def try(self, statement) -> bool:
    try:
        eval(statement)
        return True
    except:
        return False

```

This is how it works:

```
tup = (1, 2, 3)
statement = str(tup.append(4)) # potential erroneous statement
try(statement):
    # statements that execute if no error occurs
    # for example
    print (" added successfully")

```

If there already exists an alternative to this, please let me know. Else, I would like to consider this to be added as an enhanced try() function to the core module of python.

---

<div class="post-metadata">

**Author:** ![jeanas](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/jeanas/32/8115_2.png) [@jeanas](https://discuss.python.org/u/jeanas)\
**Post date:** [April 20, 2021, 8:42am UTC](https://discuss.python.org/t/enhanced-try-function/8313/2 "2021-04-20T08:42:39Z")

</div>

This sounds like you want the `else` clause of `try` statements: [Python Exceptions: An Introduction – Real Python](https://realpython.com/python-exceptions/#the-else-clause)

---

<div class="post-metadata">

**Author:** ![steven.daprano](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/steven.daprano/32/1083_2.png) [@steven.daprano](https://discuss.python.org/u/steven.daprano)\
**Post date:** [April 20, 2021, 8:43am UTC](https://discuss.python.org/t/enhanced-try-function/8313/3 "2021-04-20T08:43:39Z")

</div>

Hi Sanket,

You wrote this code:

```
try:
    # potential erroneous statement
    # other statements dependable on the above statement
except:
    pass

```

Please don’t write code like that. This is nearly always a terrible  
idea.

> **[The Most Diabolical Python Antipattern – Real Python](https://realpython.com/the-most-diabolical-python-antipattern/)**
>
> There are plenty of ways to write bad code. But in Python, one in particular reigns as king...

---

<div class="post-metadata">

**Author:** ![edusanketdk](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/edusanketdk/32/3986_2.png) [@edusanketdk](https://discuss.python.org/u/edusanketdk)\
**Post date:** [April 20, 2021, 9:03am UTC](https://discuss.python.org/t/enhanced-try-function/8313/4 "2021-04-20T09:03:48Z")

</div>

Hi Steven,

I understand what you want to say, that if any other exception occurs in the try block other than what we were expecting, that makes the code terribly hard to debug.

Thanks for pointing that out, because on the brighter side, my proposed enhanced try() function overcomes that misconception too. Because it takes targets only one statement at a time.

---

<div class="post-metadata">

**Author:** ![edusanketdk](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/edusanketdk/32/3986_2.png) [@edusanketdk](https://discuss.python.org/u/edusanketdk)\
**Post date:** [April 20, 2021, 9:09am UTC](https://discuss.python.org/t/enhanced-try-function/8313/5 "2021-04-20T09:09:10Z")

</div>

Jean, I get it. But using else statement is again going to increase the code size, which is the main concern here.

---

<div class="post-metadata">

**Author:** ![jeanas](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/jeanas/32/8115_2.png) [@jeanas](https://discuss.python.org/u/jeanas)\
**Post date:** [April 20, 2021, 9:46am UTC](https://discuss.python.org/t/enhanced-try-function/8313/6 "2021-04-20T09:46:38Z")

</div>

Is it this long though?

```auto
try:
    (1, 2).append(4)
except AttributeError:
    print("Nope")
else:
    print("Added successfully")

```

I have seen few cases where you want to execute code when no error occurs but you don’t want to do anything when there is an error.

---

<div class="post-metadata">

**Author:** ![erlendaasland](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/erlendaasland/32/4378_2.png) [@erlendaasland](https://discuss.python.org/u/erlendaasland)\
**Post date:** [April 20, 2021, 9:47am UTC](https://discuss.python.org/t/enhanced-try-function/8313/7 "2021-04-20T09:47:06Z")

</div>

Maybe I’m missing something, but your approach increases code size and (IMO) makes the code less readable. Also, @steven.daprano is quite right regarding `except:`

## Pythonic

```py3
# 6 lines:
try:
    fn()
except SomeException: # catch specific exceptions
    pass
else:
    success()

```

## “try function”

```python
# 10 lines
def try(stmt):
    try:
        eval(stmt)
        return True
    except: # oops, catch all => bad coding!
        return False

stmt = str(fn())
if try(stmt):
    success()

```

AFAICS, the pythonic way is both compact and readable, and it correctly catches specific exceptions.

---

<div class="post-metadata">

**Author:** ![daniele](https://avatars.discourse-cdn.com/v4/letter/d/dfb087/32.png) [@daniele](https://discuss.python.org/u/daniele)\
**Post date:** [April 20, 2021, 8:39pm UTC](https://discuss.python.org/t/enhanced-try-function/8313/8 "2021-04-20T20:39:04Z")

</div>

I think the `contextlib.suppress()` context manager does pretty much what you want in a much more idiomatic way than the `try()` function you propose.

---

<div class="post-metadata">

**Author:** ![erlendaasland](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/erlendaasland/32/4378_2.png) [@erlendaasland](https://discuss.python.org/u/erlendaasland)\
**Post date:** [April 20, 2021, 9:48pm UTC](https://discuss.python.org/t/enhanced-try-function/8313/9 "2021-04-20T21:48:12Z")

</div>

Oh, I’d forgotten about `contextlib.suppress()`; thanks for the reminder 😄

---

<div class="post-metadata">

**Author:** ![steven.daprano](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/steven.daprano/32/1083_2.png) [@steven.daprano](https://discuss.python.org/u/steven.daprano)\
**Post date:** [April 20, 2021, 11:33pm UTC](https://discuss.python.org/t/enhanced-try-function/8313/10 "2021-04-20T23:33:34Z")

</div>

Even one statement can contain many different possible failures.

```
a = mymodule.function(arg, number + 1, mylist[0])

```

could fail with NameError, AttributeError, TypeError or IndexError and  
that’s even before the function gets called, which could fail with  
_anything_.

The problem with try…except is not that there can be more than one  
statement inside the try. The problem is that the `except` clause will  
hide _unexpected_ errors, that is **bugs**. Your code will silently  
suppress the error and go on to do the wrong thing.

To quote Chris Smith:

> **[An Old Article I Wrote](https://cdsmith.wordpress.com/2011/01/09/an-old-article-i-wrote/)**
>
> I was asked by someone to put this old piece of writing of mine somewhere more permanent, so here it is.  A few comments off the top: This isn’t new.  I wrote it years ago. Yes, I’m a b…

“”"  
I find it amusing when novice programmers believe their main job is  
preventing programs from crashing. … More experienced programmers  
realize that correct code is great, code that crashes could use  
improvement, but incorrect code that doesn’t crash is a horrible  
nightmare.  
“”"

The Therac-25 machines killed people because their software didn’t  
crash when it should have.

> **[Therac-25](https://en.wikipedia.org/wiki/Therac-25)**
>
> The Therac-25 was a computer-controlled radiation therapy machine produced by Atomic Energy of Canada Limited (AECL) in 1982 after the Therac-6 and Therac-20 units (the earlier units had been produced in partnership with CGR of France).
> It was involved in at least six accidents between 1985 and 1987, in which patients were given massive overdoses of radiation.:425 Because of concurrent programming errors (also known as race conditions), it sometimes gave its patients radiation doses that were hu...

Your code might not be as critical as the Therac control software, but  
the princple is the same: code that silently does the wrong thing is a  
nightmare to debug when you eventually discover that it is producing  
garbage output instead of what you wanted.

With very, very few exceptions, catching “any exception at all” is the  
wrong thing to do. And for those few exceptions, being clear and  
explicit about what we are doing, with a full try…except block, is not  
a hardship unless you are trying to win a code golf competition.

Regardless of whether it is written with an explicit “except: pass” or  
implicitly with your suggested syntax, catching everything is not  
something that we should want to encourage. We shouldn’t want to make it  
easier to do than it already is.

---

<div class="post-metadata">

**Author:** ![steven.daprano](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/steven.daprano/32/1083_2.png) [@steven.daprano](https://discuss.python.org/u/steven.daprano)\
**Post date:** [April 20, 2021, 11:34pm UTC](https://discuss.python.org/t/enhanced-try-function/8313/11 "2021-04-20T23:34:52Z")

</div>

Why do you care so much about code size that it is “the main concern”?

What do you mean by code size?

- the number of bytes in your source code;

- the number of lines in your source code;

- the number of bytes in the compiled .pyc file;

- something else?

How many `try...except` blocks do you have in your code that this will  
be anything but a trivial extra number of lines of code?

I have just randomly picked out three small projects I am working on,  
just under 1000 lines of code in total, and with _one_ try…except  
block between them. So if I added an `else` clause, that would increase  
my code size by one line in a thousand.

My hard drive is pretty full at the moment, but I think even I can  
afford an extra line of code or two.

---

<div class="post-metadata">

**Author:** ![pytrumpeter](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/pytrumpeter/32/3589_2.png) [@pytrumpeter](https://discuss.python.org/u/pytrumpeter)\
**Post date:** [April 22, 2021, 12:52pm UTC](https://discuss.python.org/t/enhanced-try-function/8313/12 "2021-04-22T12:52:49Z")

</div>

> However, I don’t need some statements that will execute if an error occurs.

You probably do. At the very least, you can do something like this:

```
tup = (1, 2, 3)

try:
    tup[4]
except IndexError: # I was expecting this one
    logger.warn() # maybe log something
except Exception as e: # I wasn't expecting this one
    print(e. __class__. __name__ , e) # maybe inform the user this way or more friendly
    logger.error(e) # log the error, maybe do other clean up tasks in here
    raise
else:
    # All is well
    ...

```
