Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Detailed except | Error Handling
Mastering Python: Annotations, Errors and Environment
course content

Conteúdo do Curso

Mastering Python: Annotations, Errors and Environment

Mastering Python: Annotations, Errors and Environment

1. Annotations
2. Function Arguments in Details
3. Error Handling
4. Virtual Environment

bookDetailed 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:

12345678910111213
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))
copy

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:

12345678910111213
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))
copy

Now, the except keyword not caught the ZeroDivisionError.

You can catch certain in the row by the multiply except usage:

12345678910111213141516
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))
copy

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:

1234
try: 1 / 0 except ZeroDivisionError as error: print("Caught error:", error)
copy

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:

12345
try: # 1 / 0 "15" + 12 except Exception as error: print("Error caught:", error)
copy

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:

12345
try: "15" + 12 except TypeError: print("Saving logs in the file log.txt") # Not implemented raise
copy

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 3. Capítulo 5
some-alt