How to catch multiple exceptions in Python

4 Answers

0 votes
try:
    arr = {}
    n = arr[3]
except (KeyError, AttributeError) as e:
    print("KeyError or AttributeError")
finally:
    print("finally")


'''
run:

KeyError or AttributeError
finally

'''

 



answered Sep 25, 2017 by avibootz
0 votes
try:
    arr = {}
    n = arr.non_existing_field
except (KeyError, AttributeError) as e:
    print("KeyError or AttributeError")
finally:
    print("finally")


'''
run:

KeyError or AttributeError
finally

'''

 



answered Sep 25, 2017 by avibootz
0 votes
try:
    arr = {}
    n = arr.non_existing_field
except KeyError as e:
    print("KeyError:", e)
except AttributeError as e:
    print("AttributeError:", e)
finally:
    print("finally")


'''
run:

AttributeError: 'dict' object has no attribute 'non_existing_field'
finally

'''

 



answered Sep 25, 2017 by avibootz
0 votes
try:
    arr = {}
    n = arr[3]
except KeyError as e:
    print("KeyError:", e)
except AttributeError as e:
    print("AttributeError:", e)
finally:
    print("finally")


'''
run:

KeyError: 3
finally

'''

 



answered Sep 25, 2017 by avibootz

Related questions

2 answers 311 views
1 answer 252 views
2 answers 417 views
1 answer 168 views
1 answer 309 views
1 answer 330 views
1 answer 294 views
...