5. Exceções embutidas¶
No Python, todas as exceções devem ser instâncias de uma classe derivada de BaseException
. Em uma instrução try
com uma cláusula except
que menciona uma classe específica, essa cláusula também lida com qualquer classe de exceção derivada dessa classe (mas não com as classes de exceção a partir das quais ela é derivada). Duas classes de exceção que não são relacionadas por subclasse nunca são equivalentes, mesmo que tenham o mesmo nome.
As exceções embutidas listadas abaixo podem ser geradas pelo interpretador ou pelas funções embutidas. Exceto onde mencionado, eles têm um “valor associado” indicando a causa detalhada do erro. Pode ser uma sequência ou uma tupla de vários itens de informação (por exemplo, um código de erro e uma sequência que explica o código). O valor associado geralmente é passado como argumentos para o construtor da classe de exceção.
O código do usuário pode gerar exceções embutidas. Isso pode ser usado para testar um manipulador de exceções ou para relatar uma condição de erro “exatamente como” a situação na qual o interpretador gera a mesma exceção; mas lembre-se de que nada impede o código do usuário de gerar um erro inadequado.
As classes de exceção internas podem ser usadas como subclasses para definir novas exceções; Os programadores são incentivados a derivar novas exceções da classe Exception
ou de uma de suas subclasses, e não de BaseException
. Mais informações sobre a definição de exceções estão disponíveis no Tutorial do Python em Exceções definidas pelo usuário.
Ao gerar (ou levantar novamente) uma exceção em uma cláusula except
ou :keyword:` finally`, __context__
é automaticamente definida como a última exceção capturada; se a nova exceção não for tratada, o traceback exibido eventualmente incluirá as exceções de origem e a exceção final.
Ao levantar uma nova exceção (em vez de usar um raise
simples para aumentar novamente a exceção que está sendo tratada), o contexto implícito da exceção pode ser complementado com uma causa explícita usando from
com raise
raise new_exc from original_exc
The expression following from
must be an exception or None
. It
will be set as __cause__
on the raised exception. Setting
__cause__
also implicitly sets the __suppress_context__
attribute to True
, so that using raise new_exc from None
effectively replaces the old exception with the new one for display
purposes (e.g. converting KeyError
to AttributeError
, while
leaving the old exception available in __context__
for introspection
when debugging.
O código de exibição padrão do traceback mostra essas exceções encadeadas, além do traceback da própria exceção. Uma exceção explicitamente encadeada em __cause__
sempre é mostrada quando presente. Uma exceção implicitamente encadeada em __context__
é mostrada apenas se __cause__
for None
e __suppress_context__
for falso.
Em qualquer um dos casos, a exceção em si sempre é mostrada após todas as exceções encadeadas, de modo que a linha final do traceback sempre mostre a última exceção que foi levantada.
5.1. Classes base¶
As seguintes exceções são usadas principalmente como classes base para outras exceções.
-
exception
BaseException
¶ A classe base para todas as exceções internas. Não é para ser herdada diretamente por classes definidas pelo usuário (para isso, use
Exception
). Sestr()
for chamado em uma instância desta classe, a representação do(s) argumento(s) para a instância será retornada ou a string vazia quando não houver argumentos.-
args
¶ A tupla de argumentos fornecidos ao construtor de exceções. Algumas exceções embutidas (como
OSError
) esperam um certo número de argumentos e atribuem um significado especial aos elementos dessa tupla, enquanto outras são normalmente chamadas apenas com uma única string que fornece uma mensagem de erro.
-
with_traceback
(tb)¶ Esse método define tb como o novo retorno para a exceção e retorna o objeto de exceção. Geralmente é usado no código de manipulação de exceção como este:
try: ... except SomeException: tb = sys.exc_info()[2] raise OtherException(...).with_traceback(tb)
-
-
exception
Exception
¶ Todas as exceções embutidas que não saem para o sistema são derivadas dessa classe. Todas as exceções definidas pelo usuário também devem ser derivadas dessa classe.
-
exception
ArithmeticError
¶ A classe base para as exceções embutidas levantadas para vários erros aritméticos:
OverflowError
,ZeroDivisionError
,FloatingPointError
.
-
exception
LookupError
¶ A classe base para as exceções levantadas quando uma chave ou índice usado em um mapeamento ou sequência é inválido:
IndexError
,KeyError
. Isso pode ser levantado diretamente porcodecs.lookup()
.
5.2. Exceções concretas¶
As seguintes exceções são as que geralmente são levantados.
-
exception
AttributeError
¶ Levantado quando uma referência de atributo (consulte attribute-reference) ou atribuição falha. (Quando um objeto não oferece suporte a referências ou atribuições de atributos,
TypeError
é levantado.)
-
exception
EOFError
¶ Levantado quando a função
input()
atinge uma condição de fim de arquivo (EOF) sem ler nenhum dado. (Note: os métodosio.IOBase.read()
eio.IOBase.readline()
retornam uma string vazia quando pressionam o EOF.)
-
exception
FloatingPointError
¶ Raised when a floating point operation fails. This exception is always defined, but can only be raised when Python is configured with the
--with-fpectl
option, or theWANT_SIGFPE_HANDLER
symbol is defined in thepyconfig.h
file.
-
exception
GeneratorExit
¶ Levantado quando gerador ou coroutine está fechado; veja
generator.close()
ecoroutine.close()
. Herda diretamente deBaseException
em vez deException
, já que tecnicamente não é um erro.
-
exception
ImportError
¶ Raised when an
import
statement fails to find the module definition or when afrom ... import
fails to find a name that is to be imported.Os atributos
name
epath
podem ser configurados usando argumentos somente de palavra-chave para o construtor. Quando configurados, eles representam o nome do módulo que foi tentado ser importado e o caminho para qualquer arquivo que acionou a exceção, respectivamente.Alterado na versão 3.3: Adicionados os atributos
name
epath
.
-
exception
IndexError
¶ Levantada quando um índice de alguma sequência está fora do intervalo. (Índices de fatia são truncados sileciosamente para cair num intervalo permitido; se um índice não for um inteiro,
TypeError
é levantada.)
-
exception
KeyError
¶ Levantada quando uma chave de mapeamento (dicionário) não é encontrada no conjunto de chaves existentes.
-
exception
KeyboardInterrupt
¶ Levantada quando um usuário aperta a tecla de interrupção (normalmente Control-C ou Delete). Durante a execução, uma checagem de interrupção é feita regularmente. A exceção herda de
BaseException
para que não seja capturada acidentalmente por códigos que tratamException
e assim evita que o interpretador saia.
-
exception
MemoryError
¶ Levantada quando uma operação fica sem memória mas a situação ainda pode ser recuperada (excluindo alguns objetos). O valor associado é uma string que indica o tipo de operação (interna) que ficou sem memória. Observe que, por causa da arquitetura de gerenciamento de memória subjacente (função
malloc()
do C), o interpretador pode não ser capaz de se recuperar completamente da situação; no entanto, levanta uma exceção para que um traceback possa ser impresso, no caso de um outro programa ser a causa.
-
exception
NameError
¶ Levantada quando um nome local ou global não é encontrado. Isso se aplica apenas a nomes não qualificados. O valor associado é uma mensagem de erro que inclui o nome que não pode ser encontrado.
-
exception
NotImplementedError
¶ This exception is derived from
RuntimeError
. In user defined base classes, abstract methods should raise this exception when they require derived classes to override the method.
-
exception
OSError
([arg])¶ -
exception
OSError
(errno, strerror[, filename[, winerror[, filename2]]]) Esta exceção é levantada quando uma função do sistema retorna um erro relacionado ao sistema, incluindo falhas do tipo I/O como “file not found” ou “disk full”(não para tipos de argumentos não permitidos ou outro erro acessório.)
A segunda forma do construtor definir os atributos correspondentes, descritos abaixo. Os atributos terão valor
None
se não forem especificads. Por compatibilidade com versões anteriores, se três argumentos são passados, o atributoargs
contêm somente uma tupla de 2 elementos, os dois primeiros argumentos do construtor.O construtor geralmente retorna uma subclasse de
OSError
, como descrito abaixo em OS exceptions . A subclasse particular depende do valor final deerrno
. Este comportamento ocorre apenas durante a construção direta ou por meio de um apelido deOSError
, e não é herdado na criação de subclasses.-
errno
¶ Um código de erro numérico da variável C
errno
.
-
winerror
¶ Under Windows, this gives you the native Windows error code. The
errno
attribute is then an approximate translation, in POSIX terms, of that native error code.Under Windows, if the winerror constructor argument is an integer, the
errno
attribute is determined from the Windows error code, and the errno argument is ignored. On other platforms, the winerror argument is ignored, and thewinerror
attribute does not exist.
-
strerror
¶ The corresponding error message, as provided by the operating system. It is formatted by the C functions
perror()
under POSIX, andFormatMessage()
under Windows.
-
filename
¶ -
filename2
¶ For exceptions that involve a file system path (such as
open()
oros.unlink()
),filename
is the file name passed to the function. For functions that involve two file system paths (such asos.rename()
),filename2
corresponds to the second file name passed to the function.
Alterado na versão 3.3:
EnvironmentError
,IOError
,WindowsError
,socket.error
,select.error
andmmap.error
have been merged intoOSError
, and the constructor may return a subclass.Alterado na versão 3.4: The
filename
attribute is now the original file name passed to the function, instead of the name encoded to or decoded from the filesystem encoding. Also, the filename2 constructor argument and attribute was added.-
-
exception
OverflowError
¶ Raised when the result of an arithmetic operation is too large to be represented. This cannot occur for integers (which would rather raise
MemoryError
than give up). However, for historical reasons, OverflowError is sometimes raised for integers that are outside a required range. Because of the lack of standardization of floating point exception handling in C, most floating point operations are not checked.
-
exception
RecursionError
¶ This exception is derived from
RuntimeError
. It is raised when the interpreter detects that the maximum recursion depth (seesys.getrecursionlimit()
) is exceeded.Novo na versão 3.5: Previously, a plain
RuntimeError
was raised.
-
exception
ReferenceError
¶ This exception is raised when a weak reference proxy, created by the
weakref.proxy()
function, is used to access an attribute of the referent after it has been garbage collected. For more information on weak references, see theweakref
module.
-
exception
RuntimeError
¶ Levantada quando um erro é detectado e não se encaixa em nenhuma das outras categorias. O valor associado é uma string indicando o que precisamente deu errado.
-
exception
StopIteration
¶ Raised by built-in function
next()
and an iterator’s__next__()
method to signal that there are no further items produced by the iterator.The exception object has a single attribute
value
, which is given as an argument when constructing the exception, and defaults toNone
.When a generator or coroutine function returns, a new
StopIteration
instance is raised, and the value returned by the function is used as thevalue
parameter to the constructor of the exception.If a generator function defined in the presence of a
from __future__ import generator_stop
directive raisesStopIteration
, it will be converted into aRuntimeError
(retaining theStopIteration
as the new exception’s cause).Alterado na versão 3.3: Added
value
attribute and the ability for generator functions to use it to return a value.Alterado na versão 3.5: Introduced the RuntimeError transformation.
-
exception
StopAsyncIteration
¶ Must be raised by
__anext__()
method of an asynchronous iterator object to stop the iteration.Novo na versão 3.5.
-
exception
SyntaxError
¶ Raised when the parser encounters a syntax error. This may occur in an
import
statement, in a call to the built-in functionsexec()
oreval()
, or when reading the initial script or standard input (also interactively).Instances of this class have attributes
filename
,lineno
,offset
andtext
for easier access to the details.str()
of the exception instance returns only the message.
-
exception
IndentationError
¶ Classe base para erros de sintaxe relacionados a indentação incorreta. Esta é uma subclasse de
SyntaxError
.
-
exception
TabError
¶ Raised when indentation contains an inconsistent use of tabs and spaces. This is a subclass of
IndentationError
.
-
exception
SystemError
¶ Raised when the interpreter finds an internal error, but the situation does not look so serious to cause it to abandon all hope. The associated value is a string indicating what went wrong (in low-level terms).
You should report this to the author or maintainer of your Python interpreter. Be sure to report the version of the Python interpreter (
sys.version
; it is also printed at the start of an interactive Python session), the exact error message (the exception’s associated value) and if possible the source of the program that triggered the error.
-
exception
SystemExit
¶ This exception is raised by the
sys.exit()
function. It inherits fromBaseException
instead ofException
so that it is not accidentally caught by code that catchesException
. This allows the exception to properly propagate up and cause the interpreter to exit. When it is not handled, the Python interpreter exits; no stack traceback is printed. The constructor accepts the same optional argument passed tosys.exit()
. If the value is an integer, it specifies the system exit status (passed to C’sexit()
function); if it isNone
, the exit status is zero; if it has another type (such as a string), the object’s value is printed and the exit status is one.A call to
sys.exit()
is translated into an exception so that clean-up handlers (finally
clauses oftry
statements) can be executed, and so that a debugger can execute a script without running the risk of losing control. Theos._exit()
function can be used if it is absolutely positively necessary to exit immediately (for example, in the child process after a call toos.fork()
).-
code
¶ The exit status or error message that is passed to the constructor. (Defaults to
None
.)
-
-
exception
TypeError
¶ Raised when an operation or function is applied to an object of inappropriate type. The associated value is a string giving details about the type mismatch.
-
exception
UnboundLocalError
¶ Raised when a reference is made to a local variable in a function or method, but no value has been bound to that variable. This is a subclass of
NameError
.
-
exception
UnicodeError
¶ Raised when a Unicode-related encoding or decoding error occurs. It is a subclass of
ValueError
.UnicodeError
has attributes that describe the encoding or decoding error. For example,err.object[err.start:err.end]
gives the particular invalid input that the codec failed on.-
encoding
¶ The name of the encoding that raised the error.
-
reason
¶ A string describing the specific codec error.
-
object
¶ The object the codec was attempting to encode or decode.
-
-
exception
UnicodeEncodeError
¶ Raised when a Unicode-related error occurs during encoding. It is a subclass of
UnicodeError
.
-
exception
UnicodeDecodeError
¶ Raised when a Unicode-related error occurs during decoding. It is a subclass of
UnicodeError
.
-
exception
UnicodeTranslateError
¶ Raised when a Unicode-related error occurs during translating. It is a subclass of
UnicodeError
.
-
exception
ValueError
¶ Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as
IndexError
.
-
exception
ZeroDivisionError
¶ Raised when the second argument of a division or modulo operation is zero. The associated value is a string indicating the type of the operands and the operation.
The following exceptions are kept for compatibility with previous versions;
starting from Python 3.3, they are aliases of OSError
.
-
exception
EnvironmentError
¶
-
exception
IOError
¶
-
exception
WindowsError
¶ Only available on Windows.
5.2.1. OS exceptions¶
The following exceptions are subclasses of OSError
, they get raised
depending on the system error code.
-
exception
BlockingIOError
¶ Raised when an operation would block on an object (e.g. socket) set for non-blocking operation. Corresponds to
errno
EAGAIN
,EALREADY
,EWOULDBLOCK
andEINPROGRESS
.In addition to those of
OSError
,BlockingIOError
can have one more attribute:
-
exception
ChildProcessError
¶ Raised when an operation on a child process failed. Corresponds to
errno
ECHILD
.
-
exception
ConnectionError
¶ A base class for connection-related issues.
Subclasses are
BrokenPipeError
,ConnectionAbortedError
,ConnectionRefusedError
andConnectionResetError
.
-
exception
BrokenPipeError
¶ A subclass of
ConnectionError
, raised when trying to write on a pipe while the other end has been closed, or trying to write on a socket which has been shutdown for writing. Corresponds toerrno
EPIPE
andESHUTDOWN
.
-
exception
ConnectionAbortedError
¶ A subclass of
ConnectionError
, raised when a connection attempt is aborted by the peer. Corresponds toerrno
ECONNABORTED
.
-
exception
ConnectionRefusedError
¶ A subclass of
ConnectionError
, raised when a connection attempt is refused by the peer. Corresponds toerrno
ECONNREFUSED
.
-
exception
ConnectionResetError
¶ A subclass of
ConnectionError
, raised when a connection is reset by the peer. Corresponds toerrno
ECONNRESET
.
-
exception
FileExistsError
¶ Raised when trying to create a file or directory which already exists. Corresponds to
errno
EEXIST
.
-
exception
FileNotFoundError
¶ Raised when a file or directory is requested but doesn’t exist. Corresponds to
errno
ENOENT
.
-
exception
InterruptedError
¶ Raised when a system call is interrupted by an incoming signal. Corresponds to
errno
EINTR
.Alterado na versão 3.5: Python now retries system calls when a syscall is interrupted by a signal, except if the signal handler raises an exception (see PEP 475 for the rationale), instead of raising
InterruptedError
.
-
exception
IsADirectoryError
¶ Raised when a file operation (such as
os.remove()
) is requested on a directory. Corresponds toerrno
EISDIR
.
-
exception
NotADirectoryError
¶ Raised when a directory operation (such as
os.listdir()
) is requested on something which is not a directory. Corresponds toerrno
ENOTDIR
.
-
exception
PermissionError
¶ Raised when trying to run an operation without the adequate access rights - for example filesystem permissions. Corresponds to
errno
EACCES
andEPERM
.
-
exception
ProcessLookupError
¶ Raised when a given process doesn’t exist. Corresponds to
errno
ESRCH
.
-
exception
TimeoutError
¶ Raised when a system function timed out at the system level. Corresponds to
errno
ETIMEDOUT
.
Novo na versão 3.3: All the above OSError
subclasses were added.
Ver também
PEP 3151 - Reworking the OS and IO exception hierarchy
5.3. Warnings¶
The following exceptions are used as warning categories; see the warnings
module for more information.
-
exception
Warning
¶ Base class for warning categories.
-
exception
UserWarning
¶ Base class for warnings generated by user code.
-
exception
DeprecationWarning
¶ Base class for warnings about deprecated features.
-
exception
PendingDeprecationWarning
¶ Base class for warnings about features which will be deprecated in the future.
-
exception
SyntaxWarning
¶ Base class for warnings about dubious syntax.
-
exception
RuntimeWarning
¶ Base class for warnings about dubious runtime behavior.
-
exception
FutureWarning
¶ Base class for warnings about constructs that will change semantically in the future.
-
exception
ImportWarning
¶ Base class for warnings about probable mistakes in module imports.
-
exception
UnicodeWarning
¶ Base class for warnings related to Unicode.
-
exception
ResourceWarning
¶ Base class for warnings related to resource usage.
Novo na versão 3.2.
5.4. Exception hierarchy¶
The class hierarchy for built-in exceptions is:
BaseException
+-- SystemExit
+-- KeyboardInterrupt
+-- GeneratorExit
+-- Exception
+-- StopIteration
+-- StopAsyncIteration
+-- ArithmeticError
| +-- FloatingPointError
| +-- OverflowError
| +-- ZeroDivisionError
+-- AssertionError
+-- AttributeError
+-- BufferError
+-- EOFError
+-- ImportError
+-- LookupError
| +-- IndexError
| +-- KeyError
+-- MemoryError
+-- NameError
| +-- UnboundLocalError
+-- OSError
| +-- BlockingIOError
| +-- ChildProcessError
| +-- ConnectionError
| | +-- BrokenPipeError
| | +-- ConnectionAbortedError
| | +-- ConnectionRefusedError
| | +-- ConnectionResetError
| +-- FileExistsError
| +-- FileNotFoundError
| +-- InterruptedError
| +-- IsADirectoryError
| +-- NotADirectoryError
| +-- PermissionError
| +-- ProcessLookupError
| +-- TimeoutError
+-- ReferenceError
+-- RuntimeError
| +-- NotImplementedError
| +-- RecursionError
+-- SyntaxError
| +-- IndentationError
| +-- TabError
+-- SystemError
+-- TypeError
+-- ValueError
| +-- UnicodeError
| +-- UnicodeDecodeError
| +-- UnicodeEncodeError
| +-- UnicodeTranslateError
+-- Warning
+-- DeprecationWarning
+-- PendingDeprecationWarning
+-- RuntimeWarning
+-- SyntaxWarning
+-- UserWarning
+-- FutureWarning
+-- ImportWarning
+-- UnicodeWarning
+-- BytesWarning
+-- ResourceWarning