How do I get an error but continue the script in python?
Suppose I have this code in Python:
l = dict['link']
t = dict['title'] <<<<<<<<error here, there is no "title"
d = dict['description']
k = dict['keyword']
What if there is an error on line 2, but I want it to continue running the script and assign different values? Can I just "ignore" errors?
EDIT: I know how to do a simple try, except. However, often when there is an error at # 2, it will fire at the except and then NOT continue with the rest of the code. '
EDIT: I understand there is a "get" method. However, I would like to use GENERAL ... I will not always use dictionaries.
source to share
The easiest option is to use .get()
:
l = dict.get('link')
t = dict.get('title')
d = dict.get('description')
k = dict.get('keyword')
The variable t
will then contain None
(you can use dict.get('title', '')
an empty string if you like, for example). Another option is to catch the exception KeyError
.
source to share
If you want to use exceptions and keep going (although this is probably not a good idea) you can use a wrapper function such as:
def consume_exception(func, args, exception):
try:
return func(*args)
except exception:
return None
Or something like that.
Then call
l = consume_exception(dict.__getitem__, ['link'], KeyError) t = consume_exception(dict.__getitem__, ['title'], KeyError) ...
source to share