Handling Multiple Exceptions
Lesson 8 of 16 in Coddy's Exception Handling in Python course.
Suppose, there is a possibility of multiple Exceptions in your code. You can handle all Exceptions by following way.
try:
code which can cause
TypeError, ValueError, ZeroDivisionError
except (TypeError, ValueError, ZeroDivisionError) as obj:
print(obj)If any of above three Exceptions happens, control goes to except block and program isn't get terminated.
Handle any Exception:
If you are not sure which exception will occur, do not write anything after except keyword.
try:
code which can cause
TypeError, ValueError, ZeroDivisionError
except:
print("Something went wrong")Above syntax will handle any exception from try block. But, you won't have object here to print information.
Use below syntax:
try:
code which can cause
TypeError, ValueError, ZeroDivisionError
except Exception as obj:
print(obj)Above syntax will handle any exception raised in try block and you can print message using obj.
Challenge
EasyComplete function 'calculator' which takes two integers as arguments and performs division. Handle all causing Exceptions and print standard message. If no Exception, print result using else block.
Try it yourself
def calculator(n1,n2):
#your code goes hereAll lessons in Exception Handling in Python
4Customization/best practices
Customize Tracebacks2Exception Handling
try-exceptelseFinallyPrinting Exception messagePrinting Exception NameHandling Multiple Exceptionssys module for information