Contenido del Curso
Mastering Python: Annotations, Errors and Environment
Mastering Python: Annotations, Errors and Environment
Examples
Let's consider the most useful exceptions in Python.
TypeError
This exception is raised when a function takes the value with an unexpected type.
print("First print") len(15) print("Second print")
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.
from math import sqrt print("First print") sqrt(-5) print("Second print")
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
:
print("First print") 124 / 0 print("Second print")
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:
print("First print") print("Second print") print("Third print
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.
¡Gracias por tus comentarios!