Course Content
Mastering Python: Annotations, Errors and Environment
Mastering Python: Annotations, Errors and Environment
Detailed except
You can catch certain types of errors using the except
keyword.
There are moments when you need to catch certain errors and handle them. For example, you need to handle the TypeError
, but executing raises the ZeroDivisionError
. If you handle ZeroDivisionError
like the TypeError
- it is a bug:
def division(a, b): try: if not isinstance(a, (int, float)): raise TypeError if not isinstance(b, (int, float)): raise TypeError return a / b except: print("The received agruments is not int/float.") print(division(5, 0))
In the example above, the ZeroDivisionError
was raised by the 5 / 0
expression. The except
catch it and print the wrong message.
To catch the certain error, you should write the error name after the except
keyword:
def division(a, b): try: if not isinstance(a, (int, float)): raise TypeError if not isinstance(b, (int, float)): raise TypeError return a / b except TypeError: print("The received agruments is not int/float.") print(division(5, 0))
Now, the except
keyword not caught the ZeroDivisionError
.
You can catch certain in the row by the multiply except
usage:
def division(a, b): try: if not isinstance(a, (int, float)): raise TypeError if not isinstance(b, (int, float)): raise TypeError return a / b except TypeError: print("The received agruments is not int/float.") except ZeroDivisionError: print("The ZeroDivisionError was caught") print(division(5, 0))
Error info usage
You can save the error using the as
keyword after the except
and error type. You should name this error, and you can use it like the variable:
try: 1 / 0 except ZeroDivisionError as error: print("Caught error:", error)
In the example above, the caught error is saved into the error
variable by the as
keyword.
To catch any exception with the as
keyword, you can use the Exception
object:
try: # 1 / 0 "15" + 12 except Exception as error: print("Error caught:", error)
You can add and remove comments in the example above to understand how it works.
Reraising
You can reraise the exception, which can be needed for specific cases. To reraise the exception, you should use the raise
keyword without anything:
try: "15" + 12 except TypeError: print("Saving logs in the file log.txt") # Not implemented raise
Thanks for your feedback!