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.
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
I'm writing a script that will interract with a website. Most of the handling of the website itself is in 1 function. Websites can of course change at any time and something as simple as the XPath of some element slightly changing can cause an exception to be thrown.
I'm wondering if there's a way to have a catch-all, like "if any expection is thrown in this function, execute this instead." For what i'm doing, i don't want 1 excpetion or unexpected behavior to terminate my entire script. I'd just want to log what happened, and continue on. Using a try except block for every instance of interracting with web elements would be tedious and quite frankly ugly coding and become annoying to maintain. Is there any way to basically have a default exception caught function?
Edit: if relevant, i'm using selenium to interract with websites. I'm also using multithreading to have multiple tabs open, so i don't want 1 tab having an issue causing all the other 10 to close out
Handling exceptions in Python like a pro
Should I catch all exceptions?
Only catch when you have something meaningful to do in response.* Do not return instances of Exception; that makes the caller have to check whether the returned value was an Exception or not, which isn't how it's intended to be used, and denies the caller the option of passing on an exception to something that can handle it reasonably.
Sometimes, "translating" an exception into a different exception type makes sense.
* On rare occasions, "nothing" can be a meaningful action: the semantics are that you don't care that something went wrong and the best way to handle it is to proceed as if you'd never tried in the first place, and you can be sure that trying hasn't changed any global state that needs to be restored. My best example of this is if you're making a game and you try to play a sound, and the sound-handling code raises an exception because that specific audio file couldn't be opened - what else are you going to do? It's probably silly to tear the whole game down and say "sorry you can't play because this one sound doesn't work right", and there's probably nothing you can replace the sound with. Maybe you can make a note or something to not try the same sound again in the future; but OTOH, maybe the problem was temporary. Just because you opened the file doesn't mean it's been deleted, and even then, maybe it will be restored. Of course, that's different again if you have pre-packaged resources somehow; but I mean you can go back and forth on this kind of thing forever.
More on reddit.com