No, you cannot do that. That's just the way Python has its syntax. Once you exit a try-block because of an exception, there is no way back in.
What about a for-loop though?
funcs = do_smth1, do_smth2
for func in funcs:
try:
func()
except Exception:
pass # or you could use 'continue'
Note however that it is considered a bad practice to have a bare except. You should catch for a specific exception instead. I captured for Exception because that's as good as I can do without knowing what exceptions the methods might throw.
Best practices for try/except blocks in Python script.
Catch exception and continue try block in Python - Stack Overflow
exception - Catch any error in Python - Stack Overflow
python - How can I write a `try`/`except` block that catches all exceptions? - Stack Overflow
Should I catch multiple exceptions separately or together?
When should I use try/except vs just letting the script crash?
How do I write error messages that are actually useful?
Videos
I am writing a python script to interact with an instrument. The instrument comes with a python library that I am using in my script.
I am not sure what might be the best practice for using try/except blocks in Python.
Approach 1:
try: some_command_1 except Exception as e: logger.exception(e) try: some_command_2 except Exception as e: logger.exception(e) . . . try: some_command_n except Exception as e: logger.exception(e)
Approach 2:
def main():
command_1()
command_2()
command_n()
if __name__ == "__main__":
try:
main()
except Exception as e:
logger.exception(e)When there is an error that raises to a level of an exception, I don't want my script to just catch the exception and move on to the next step.
The step where this error could have occurred might be critical that it is not necessary to proceed with the execution of the remainder of the script.
I am thinking that Approach 2 might be the best approach for my problem. But is it a good practice to do it this way?
The type of error that raises to the level of exception include: Instrument has a problem that it doesn't want to execute the command, lost communications etc.
No, you cannot do that. That's just the way Python has its syntax. Once you exit a try-block because of an exception, there is no way back in.
What about a for-loop though?
funcs = do_smth1, do_smth2
for func in funcs:
try:
func()
except Exception:
pass # or you could use 'continue'
Note however that it is considered a bad practice to have a bare except. You should catch for a specific exception instead. I captured for Exception because that's as good as I can do without knowing what exceptions the methods might throw.
While the other answers and the accepted one are correct and should be followed in real code, just for completeness and humor, you can try the fuckitpy ( https://github.com/ajalt/fuckitpy ) module.
Your code can be changed to the following:
@fuckitpy
def myfunc():
do_smth1()
do_smth2()
Then calling myfunc() would call do_smth2() even if there is an exception in do_smth1())
Note: Please do not try it in any real code, it is blasphemy
Using except by itself will catch any exception short of a segfault.
try:
something()
except:
fallback()
You might want to handle KeyboardInterrupt separately in case you need to use it to exit your script:
try:
something()
except KeyboardInterrupt:
return
except:
fallback()
There's a nice list of basic exceptions you can catch here. I also quite like the traceback module for retrieving a call stack from the exception. Try traceback.format_exc() or traceback.print_exc() in an exception handler.
try:
# do something
except Exception, e:
# handle it
For Python 3.x:
try:
# do something
except Exception as e:
# handle it
Apart from a bare except: clause (which as others have said you shouldn't use), you can simply catch Exception:
import traceback
import logging
try:
whatever()
except Exception as e:
logging.error(traceback.format_exc())
# Logs the error appropriately.
You would normally only ever consider doing this at the outermost level of your code if for example you wanted to handle any otherwise uncaught exceptions before terminating.
The advantage of except Exception over the bare except is that there are a few exceptions that it wont catch, most obviously KeyboardInterrupt and SystemExit: if you caught and swallowed those then you could make it hard for anyone to exit your script.
You can but you probably shouldn't:
try:
do_something()
except:
print("Caught it!")
However, this will also catch exceptions like KeyboardInterrupt and you usually don't want that, do you? Unless you re-raise the exception right away - see the following example from the docs:
try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except IOError as (errno, strerror):
print("I/O error({0}): {1}".format(errno, strerror))
except ValueError:
print("Could not convert data to an integer.")
except:
print("Unexpected error:", sys.exc_info()[0])
raise