In Python, all exceptions must be instances of a class that derives from Show The built-in exceptions listed below can be generated by the interpreter or built-in functions. Except where mentioned, they have an “associated value” indicating the detailed cause of the error. This may be a string or a tuple of several items of information (e.g., an error code and a string explaining the code). The associated value is usually passed as arguments to the exception class’s constructor. User code can raise built-in exceptions. This can be used to test an exception handler or to report an error condition “just like” the situation in which the interpreter raises the same exception; but beware that there is nothing to prevent user code from raising an inappropriate error. The built-in exception classes can be subclassed to define new exceptions; programmers are encouraged to derive new exceptions from the Exception context¶When raising a new exception while another exception is already being handled, the new exception’s This implicit exception context can be supplemented with an explicit cause by using raise new_exc from original_exc The expression following
The default traceback display code shows these chained exceptions in addition to the traceback for the exception itself. An explicitly chained exception in In either case, the exception itself is always shown after any chained exceptions so that the final line of the traceback always shows the last exception that was raised. Inheriting from built-in exceptions¶User code can create subclasses that inherit from an exception type. It’s recommended to only subclass one exception type at a time to avoid any possible conflicts between how the bases handle the CPython implementation detail: Most built-in exceptions are implemented in C for efficiency, see: Objects/exceptions.c. Some have custom memory layouts which makes it impossible to create a subclass that inherits from multiple exception types. The memory layout of a type is an implementation detail and might change between Python versions, leading to new conflicts in the future. Therefore, it’s recommended to avoid subclassing multiple exception types altogether. Base classes¶The following exceptions are used mostly as base classes for other exceptions. exceptionBaseException ¶
The base class for all built-in exceptions. It is not meant to be directly inherited by user-defined classes (for that, use args ¶The tuple of arguments given to the exception constructor. Some built-in exceptions (like with_traceback (tb)¶This method sets tb as the new traceback for the exception and returns the exception object. It was more commonly used
before the exception chaining features of PEP 3134 became available. The following example shows how we can convert an instance of try: ... except SomeException: tb = sys.exc_info()[2] raise OtherException(...).with_traceback(tb)exception Exception ¶All built-in, non-system-exiting exceptions are derived from this class. All user-defined exceptions should also be derived from this class. exceptionArithmeticError ¶The base class for those built-in exceptions that are raised for various arithmetic errors: BufferError ¶Raised when a buffer related operation cannot be performed. exceptionLookupError ¶The base class for the exceptions that are raised when a key or index used on a mapping or sequence is invalid:
Concrete exceptions¶The following exceptions are the exceptions that are usually raised. exceptionAssertionError ¶Raised when an
AttributeError ¶Raised when an attribute reference (see Attribute
references) or assignment fails. (When an object does not support attribute references or attribute assignments at all, The Changed in version 3.10: Added the EOFError ¶Raised when the FloatingPointError ¶Not currently used. exceptionGeneratorExit ¶Raised when a generator or coroutine is closed; see ImportError ¶Raised when the The Changed in version 3.3: Added the ModuleNotFoundError ¶
A subclass of New in version 3.6. exceptionIndexError ¶Raised when a sequence subscript is out of range. (Slice indices are silently truncated to fall in the allowed range; if an index is not an integer, KeyError ¶Raised when a mapping (dictionary) key is not found in the set of existing keys. exceptionKeyboardInterrupt ¶Raised
when the user hits the interrupt key (normally Control-C or Delete). During execution, a check for interrupts is made regularly. The exception inherits from Note Catching a MemoryError ¶Raised when an operation runs out of memory but the situation may still be rescued (by deleting some objects). The associated value is a string indicating what kind of (internal) operation ran out of memory. Note that because of the underlying memory management architecture (C’s NameError ¶Raised when a local or global name is not found. This applies only to unqualified names. The associated value is an error message that includes the name that could not be found. The Changed in version 3.10: Added the NotImplementedError ¶This exception is derived from Note It should not be used to indicate that an operator or method is not meant to be supported at all – in that case either leave the operator / method undefined or, if a subclass, set it to Note
OSError ([arg])¶ exception
OSError (errno, strerror[, filename[, winerror[, filename2]]])This exception is raised when a system function returns a system-related error, including I/O failures such as “file not found” or “disk full” (not for illegal argument types or other incidental errors). The second form of the constructor
sets the corresponding attributes, described below. The attributes default to The constructor
often actually returns a subclass of errno ¶A numeric error code from the C variable winerror ¶Under Windows, this gives you the native Windows error code. The Under Windows, if the winerror
constructor argument is an integer, the strerror ¶The corresponding error message, as provided by the operating system. It is formatted by the C functions filename ¶ filename2 ¶For exceptions that involve a file system path (such as
Changed in version 3.4: The OverflowError ¶Raised when the result of an arithmetic operation is too large to be represented. This cannot occur for integers (which would rather raise RecursionError ¶This exception is derived from
New in version 3.5: Previously, a plain ReferenceError ¶This exception is raised when a weak reference proxy, created by the RuntimeError ¶Raised when an error is detected that doesn’t fall in any of the other categories. The associated value is a string indicating what precisely went wrong. exceptionStopIteration ¶Raised by built-in function The exception object has a single attribute When a generator or coroutine function returns, a new If a generator code directly or indirectly raises Changed in version 3.3: Added Changed in version 3.5: Introduced the RuntimeError transformation via Changed in version 3.7: Enable PEP 479 for all code by default: a StopAsyncIteration ¶Must be raised by New in version 3.5. exceptionSyntaxError (message, details)¶Raised when the parser encounters a syntax error. This may occur in an
The filename ¶The name of the file the syntax error occurred in. lineno ¶Which line number in the file the error occurred in. This is 1-indexed: the first line in the file has a offset ¶The column in the line where the error occurred. This is 1-indexed: the first character in the line has an text ¶The source code text involved in the error. end_lineno ¶Which line number in the file the error occurred ends in. This is 1-indexed: the first line in the file has a end_offset ¶The column in the end line where the error occurred finishes. This is 1-indexed: the first character in the line has an For errors in f-string fields, the message is prefixed by “f-string: ” and the offsets are offsets in a text constructed from the replacement expression. For example, compiling f’Bad {a b} field’ results in this args attribute: (‘f-string: …’, (‘’, 1, 2, ‘(a b)n’, 1, 5)). exceptionIndentationError ¶Base class for syntax errors related to incorrect indentation. This is a subclass of
TabError ¶Raised when indentation contains an inconsistent use of tabs and spaces. This is a subclass of
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 ( SystemExit ¶This exception is raised by the A call to
code ¶The exit status or error message that is passed to the constructor. (Defaults to 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. This exception may be raised by user code to indicate that an attempted operation on an object is not supported, and is not meant to be. If an object is meant to support a given operation but has not yet provided an implementation,
Passing arguments of the wrong type (e.g. passing a 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 UnicodeError ¶Raised when a Unicode-related encoding or decoding error occurs. It is a subclass of
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. start ¶The first index of invalid data in end ¶The index after the last invalid data in UnicodeEncodeError ¶Raised when a Unicode-related error occurs during encoding. It is a subclass of UnicodeDecodeError ¶Raised when a Unicode-related error occurs during decoding. It is a subclass of UnicodeTranslateError ¶Raised when a Unicode-related error occurs during translating. It is a subclass of ValueError ¶Raised when an 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 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
EnvironmentError ¶ exception
IOError ¶ exception WindowsError ¶Only available on Windows. OS exceptions¶The following exceptions are subclasses of BlockingIOError ¶Raised when an operation would block on an object (e.g. socket) set for non-blocking operation. Corresponds to In addition to those of
characters_written ¶An
integer containing the number of characters written to the stream before it blocked. This attribute is available when using the buffered I/O classes from the ChildProcessError ¶Raised when an operation on a child process failed. Corresponds to ConnectionError ¶A base class for connection-related issues. Subclasses
are BrokenPipeError ¶A subclass of ConnectionAbortedError ¶A subclass of ConnectionRefusedError ¶A subclass of
ConnectionResetError ¶A subclass of FileExistsError ¶Raised when trying to create a file or directory which already exists. Corresponds to FileNotFoundError ¶Raised when a file or directory is requested but doesn’t exist. Corresponds to InterruptedError ¶Raised when a system call is interrupted by an incoming signal. Corresponds to Changed in version 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
IsADirectoryError ¶Raised when a file operation (such as NotADirectoryError ¶Raised when a directory operation (such as
PermissionError ¶Raised when trying to run an operation without the adequate access rights - for example filesystem permissions. Corresponds to ProcessLookupError ¶Raised when a given process doesn’t exist. Corresponds to TimeoutError ¶Raised when a system function timed out at the system level. Corresponds to New in version 3.3: All the above See also PEP 3151 - Reworking the OS and IO exception hierarchy Warnings¶The following exceptions are used as warning categories; see the Warning Categories documentation for more details. exceptionWarning ¶Base class for warning categories. exceptionUserWarning ¶Base class for warnings generated by user code. exceptionDeprecationWarning ¶Base class for warnings about deprecated features when those warnings are intended for other Python developers. Ignored by the default warning filters, except in the The deprecation policy is described in PEP 387. exceptionPendingDeprecationWarning ¶Base class for warnings about features which are obsolete and expected to be deprecated in the future, but are not deprecated at the moment. This class is rarely used as emitting a warning about a possible upcoming deprecation is unusual, and
Ignored by the default warning filters. Enabling the Python Development Mode shows this warning. The deprecation policy is described in PEP 387. exceptionSyntaxWarning ¶Base class for warnings about dubious syntax. exceptionRuntimeWarning ¶Base class for warnings about dubious runtime behavior. exceptionFutureWarning ¶Base class for warnings about deprecated features when those warnings are intended for end users of applications that are written in Python. exceptionImportWarning ¶Base class for warnings about probable mistakes in module imports. Ignored by the default warning filters. Enabling the Python Development Mode shows this warning. exceptionUnicodeWarning ¶Base class for warnings related to Unicode. exceptionEncodingWarning ¶Base class for warnings related to encodings. See Opt-in EncodingWarning for details. New in version 3.10. exceptionBytesWarning ¶Base class for warnings related to ResourceWarning ¶Base class for warnings related to resource usage. Ignored by the default warning filters. Enabling the Python Development Mode shows this warning. New in version 3.2. 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 | +-- ModuleNotFoundError +-- 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 +-- EncodingWarning +-- ResourceWarning What is meant by raising an exception?Raising an exception is a technique for interrupting the normal flow of execution in a program, signaling that some exceptional circumstance has arisen, and returning directly to an enclosing part of the program that was designated to react to that circumstance.
What is the purpose of raising an exception in your code?While syntax errors occur when Python can't parse a line of code, raising exceptions allows us to distinguish between regular events and something exceptional, such as errors (e.g. dividing by zero) or something you might not expect to handle.
When should you raise an exception Python?Use raise when you know you want a specific behavior, such as: raise TypeError("Wanted strawberry, got grape.") Raising an exception terminates the flow of your program, allowing the exception to bubble up the call stack. In the above example, this would let you explicitly handle TypeError later.
What does raise () do in Python?The raise keyword is used to raise an exception. You can define what kind of error to raise, and the text to print to the user.
|