Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Examples | 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

bookExamples

Let's consider the most useful exceptions in Python.

TypeError

This exception is raised when a function takes the value with an unexpected type.

12345
print("First print") len(15) print("Second print")
copy

The len() function returns the length of the received data. The int type hasn't length (the len() function doesn't work with the int data type), so the interpreter raises the TypeError.

ValueError

This exception is raised when a function or method takes an unexpected value.

12345678
from math import sqrt print("First print") sqrt(-5) print("Second print")
copy

The imported sqrt() function returns the square root of a number. In the example above, the sqrt() function received -5 (negative number), but the square root cannot be taken from a negative number, so the interpreter raises the ValueError.

ZeroDivisionError

It is a well-known fact: you cannot divide by zero. The interpreter also understands this and therefore raises a ZeroDivisionError:

12345
print("First print") 124 / 0 print("Second print")
copy

SyntaxError

This is an exception of a completely different nature. If previous exceptions were raised by the interpreter, the SyntaxError raises by the linter.

Note

The linter is a tool that analyses your code before executing.

If other errors are raised during program execution, SyntaxError is raised before execution.

Look at the example:

123
print("First print") print("Second print") print("Third print
copy

Pay attention that the two first prints are not executed. In the previous exception cases (TypeError, ValueError, and ZeroDivisionError), all code before the exception was executed.

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

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