简体   繁体   中英

How do I catch all of these exceptions in python?

I am making a python program that takes in user input and uses exec() to execute it. Here is my code so far:

>>> while True:
...     var = raw_input('Enter the code: ')
...     exec(var)
...

This part works. However, I want to catch whenever the user enters input that raises an error, but I also want to print the error. This is what I did:

>>> while True:
...     try:
...             var = raw_input('Enter the code: ')
...             exec(var)
...     except * as e:
...             print e
...

This raises its own error:

  File "<stdin>", line 4
    except * as e:
           ^
SyntaxError: invalid syntax

Why is this? Isn't this the correct syntax for excepting?

The syntax for using * is only used in imports. You want to use Exception as e , and then call e later as the error message.

The correct syntax would be:

try:
    # some code
except Exception as e:
    print e

That is not the correct syntax, here is your edited code:

>>> while True:
...     try:
...             var = raw_input('Enter the code: ')
...             exec(var)
...     except Exception as e:
...             print e
...

Instead of except * as e , use except Exception as e , because * as no value associated with it except in imports. However, I would suggest that you keep your try: ... except: ... 's as little as possible, so remove the raw_input() from the try, unless you really want to surround that too.

You've got a syntax error, not an exception in your code. The correct syntax for catching all exceptions is

try:
    <your code>
except Exception as e:
    print e

"Exception" is the root of the exception hierarchy, so it catches all program (but not system) errors. See Section 8: Errors and Exceptions of the python tutorial.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM