When something goes wrong an exception is raised. For example, if you try to divide by zero,ZeroDivisionError
is raised or if you try to access a nonexistent key in a dictionary,KeyError
is raised.
empty_dict={}# empty_dict['key'] # Uncomment to see the traceback
try-except
structure¶If you know that a block of code can fail in some manner, you can usetry-except
structure to handle potential exceptions in a desired way.
# Let's try to open a file that does not existfile_name="not_existing.txt"try:withopen(file_name)asmy_file:print("File is successfully open")exceptFileNotFoundErrorase:print(f"Uups, file:{file_name} not found")print(f"Exception:{e} was raised")
Uups, file: not_existing.txt not foundException: [Errno 2] No such file or directory: 'not_existing.txt' was raised
If you don't know the type of exceptions that a code block can possibly raise, you can useException
which catches all exceptions. In addition, you can have multipleexcept
statements.
defcalculate_division(var1,var2):result=0try:result=var1/var2exceptZeroDivisionErrorasex1:print("Can't divide by zero")exceptExceptionasex2:print(f"Exception:{ex2}")returnresultresult1=calculate_division(3,3)print(f"result1:{result1}")result2=calculate_division(3,"3")print(f"result2:{result2}")result3=calculate_division(3,0)print(f"result3:{result3}")
result1: 1.0Exception: unsupported operand type(s) for /: 'int' and 'str'result2: 0Can't divide by zeroresult3: 0
try-except
can be also in outer scope:
defcalculate_division(var1,var2):returnvar1/var2try:result=calculate_division(3,"3")exceptExceptionase:print(e)
unsupported operand type(s) for /: 'int' and 'str'
In your own applications, you can use custom exceptions for signaling users about errors which occur during your application run time.
importmath# Define your own exceptionclassNegativeNumbersNotSupported(Exception):pass# Dummy example how to use your custom exceptiondefsecret_calculation(number1,number2):ifnumber1<0ornumber2<0:msg=f"Negative number in at least one of the parameters:{number1},{number2}"raiseNegativeNumbersNotSupported(msg)returnmath.sqrt(number1)+math.sqrt(number2)# Uncomment to see the traceback# result = secret_calculation(-1, 1)