0

What's a recommended way to handle all the exceptions in a python script to save it from crashing? Should I wrap the whole code into "try ... except"? Is there other, more wise way?

Kurama
  • 569
  • 2
  • 6
  • 14
  • Depends on why it's crashing. The try...catch will allow you to end more gracefully... if, for example, the script isn't properly catching an exception elsewhere, it should. – AlG Dec 21 '16 at 17:48
  • 1
    There isn't some magic general "save it from crashing" code you can apply to fix every bug that would make your code crash. We'd all love for something like that to exist, but programming isn't that simple. – user2357112 Dec 21 '16 at 17:53
  • 1
    In my answer below, I link to an article which explains why wrapping everything in a try: except: block is a bad idea because it (may/can) hide various other problems within your script logic. Exception handling should be more specific. By default if there is an unhandled exception then the python runtime will print the exception and stacktrace- which is usually what you want to happen. – Alex G Rice Dec 21 '16 at 18:18

4 Answers4

1

Yes, to make sure it exits gracefully you can do

try:
  your code
except:
  print("Uh oh!")

however, be careful as to not silence errors completely, let the user know that something has gone wrong so that you can fix it. You might want to even print the error message.

try:
  your code
except Exception as err:
  print("Uh oh, please send me this message: '" + err + "'")
Max
  • 1,325
  • 9
  • 20
1

Use try and except definitely

try:
    print('This code be running') # your code here
except Exception as e:
    print('This code NOT be running because of', e)
skrrgwasme
  • 9,358
  • 11
  • 54
  • 84
Mr.Riply
  • 825
  • 1
  • 12
  • 34
  • 3
    Please refrain from using curse words here. SO should be treated like a professional resource with language that would be appropriate in the workplace. – skrrgwasme Dec 21 '16 at 18:15
0

Handling/catching all exceptions is a Python antipattern. Check this out

https://realpython.com/blog/python/the-most-diabolical-python-antipattern/

"The following bit of code is one of the most self-destructive things a Python developer can write:"

try:
    do_something()
except:
    pass

edit:

why not to write except Exception

"There are variants that amount to the same thing – saying “except Exception:” or “except Exception as e:”, for example. They all do the same massive disservice: silently and invisibly hiding error conditions that can otherwise be quickly detected and dispatched."

Alex G Rice
  • 1,561
  • 11
  • 16
0

You can see my full explanation here,

but I would strongly encourage the use of, at the very minimum:

import traceback
import datetime

while True:
  try:
    # your code
  except:
    with open("exceptions.log", "a") as log:
      log.write("%s: Exception occurred:\n" % datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
      traceback.print_exc(file=log)

For small scripts this should be sufficient, for larger scripts, I'd recommend using pythons built-in logging, which offers a lot more power for very little extra work.

Community
  • 1
  • 1
TemporalWolf
  • 7,727
  • 1
  • 30
  • 50
  • IMHO this is not always the best way to go. I had a coworker who was doing this type of thing in a Flask web app. Except his logging config was messed up so the exceptions were disappearing. The best solution was to remove all the try: except: blocks he had wrapped around *everything* and instead let Flask handle the exception logging, which it did very well, in addition to returning the correct status code (500) to the browser. – Alex G Rice Dec 21 '16 at 18:14
  • 1
    @AlexGRice That's great if you're using Flask. Also, I note in my full explanation this is generally a bad idea, but if you have to do it, this is the way. – TemporalWolf Dec 21 '16 at 18:31