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.
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
.
t = dic.get('title')
will not result in an error. this is equivalent to:
try:
t = dic['title']
except KeyError:
t = None
and please no shadow inline, don't use dict
for variable name. use something else.
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) ...
In this case, it is best to use
l = dict.get('link', 'default')
t = dict.get('title', 'default')
and etc.
Any values that were not in the dictionary will be set to 'default'
(or whatever you choose). Of course, you'll have to deal with this later ...
Ever heard of Try Catch and Exception Handling? You can read on them here
However, you have to shy away from bugs, why do you have code that you know will fail?
Try / except / finally; see tutorial
However, the main question is, why are you assigning these variables in the first place instead of accessing the dictionary?
Use exceptions
try:
l = dict['link']
t = dict['title']
d = dict['description']
k = dict['keyword']
except (RuntimeError, TypeError, NameError):
print ('something')