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 178 views
1 answer 161 views
2 answers 286 views
1 answer 89 views
1 answer 211 views
1 answer 206 views
1 answer 204 views
...