x 3.10.6

Built-in Exceptions

All exceptions must be instances of a class that derives from BaseException.

In a try: block with an except cause: clause that mentions a particular class, that clause handles any exception classes derived from that class (but not exception classes from which it is derived).
Two exception classes that are not related via subclassing are never equivalent, even if they have the same name.

except: aka except BaseExceptions: # accepts all exception except Exception as e: # does not catch ^c ,SystemExit

try:pycom.nvs_get('wake')
except Exception as e: print(':'+str(e)+':')  #  Good only 1 attribute(in this case!)          NG  print e.message, e.args  NG  (python 2?)
:No matching object for the provided key:       
Exceptions have an associated value, string or tuple, indicating the detailed cause of the error usually passed as arguments to the exception class's constructor.

User code can raise built-in exceptions, to test an exception handler or to report an error condition

Exception classes can be subclassed to define exceptions with more detail.
Derive new exceptions from the Exception class or one of its subclasses, not from BaseExceptio n.

Exception context

Raising an exception while another exception is being handled results in the new exception's __context__ attribute to be set to the handled exception.

An exception may be handled when an except cause: or finally: clause, or a with: statement, is used.

This implicit exception context can be supplemented with an explicit cause by using 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 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), leaving the old exception available in __context__ for inspection when debugging.

The default traceback display code shows chained exceptions in addition to the traceback for the exception itself.
An explicitly chained exception in __cause__ is always shown when present.
An implicitly chained exception in __context__ is shown only if __cause__ is None and __suppress_context__ is false.

the exception 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. Only subclass one exception type at a time to avoid conflicts between how the bases handle the args attribute

Base classes

BaseException base class for built-in exceptions, not meant to be directly inherited by user-defined classes (use Exception(sic)).

str() called on an instance of this class, the representation of the argument(s) is returned, or the empty string when there were no arguments.

args The tuple of arguments given to the exception constructor.
Some built-in exceptions (like OSError) expect a specific number of arguments and assign meaning to the elements.
Some are called with a string giving an error message.

with_traceback(tb) Sets tb as the new traceback for the exception and returns the exception object.

Example showing converting an instance of SomeException into an instance of OtherException preserving the traceback.
Once raised, the current frame is pushed onto the traceback of the OtherException, as would have happened to the traceback of the original SomeException had it been allowed to propagate to the caller.

try:
    …
except SomeException:
    tb = sys.exc_info()[2]
    raise OtherException(...).with_traceback(tb)
KeyboardInterrupt User pressed the interrupt key (normally control-c or delete). Inherits from BaseException
Raised at unpredictable points and leave the program in an inconsistent state.
It is generally best to have KeyboardInterrupt end the program. (See Note on Signal Handlers and Exceptions.)
Exception(sic) Built-in, non-system-exiting exceptions are derived from this class as should user-defined exceptions
ArithmeticError base class for those built-in exceptions that are raised for various arithmetic errors: OverflowError, ZeroDivisionError, unused FloatingPointError.
  OverflowError Result of an arithmetic operation is too large to be represented. Sometimes raised for integers that are outside a required range. Cannot occur for integers (which would rather raise MemoryError than give up).
Most floating point operations are not checked.
  ZeroDivisionError Division or modulo is zero. The associated value is a string
BufferError buffer related operation cannot be performed.
LookupError key or index used on a mapping or sequence is invalid:
IndexError, KeyError. can be raised directly by codecs.lookup().

Concrete exceptions

error that doesn't fall in any of the other categories. The associated value is a string
AssertionError assert statement fails.
EOFError input() function hits an end-of-file condition (EOF) without reading any data.
io.IOBase.read() and io.IOBase.readline() return an empty string on EOF.)
GeneratorExit generator or coroutine is closed. It directly inherits from BaseException instead of Exception since it is technically not an error.
ImportError import cannot load a module or the from list has a name that cannot be found.
The name and path can be set using keyword-only arguments to the constructor.
Subclass    ModuleNotFoundError a module could not be located or None is found in sys.modules .
AttributeError attribute reference or assignment fails.
The name and obj attributes can be set using keyword-only arguments to the constructor. When set they represent the name of the attribute that was attempted to be accessed and the object that was accessed for said attribute.
ValueError 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 IndexError .
IndexError Sequence subscript is out of range.
Slice indices are truncated to fall in the allowed range.
TypeError Passing arguments of the wrong type (e.g. passing a list when an int is expected)
For an index, index is not an integer, See bad index.
or An object does not support either attribute references or assignments
NameError The unqualified name is not found. The value is an error message that includes the name. The name attribute can be set using a keyword-only argument to the constructor. When set it represents the name of the variable that was attempted to be accessed.
UnboundLocalError    A reference is made to a local variable in a function or method, but no value has been bound to that variable.
KeyError a mapping (dictionary) key is not found in the set of existing keys.
MemoryError An operation ran out of memory. This may be recovered from by deleting some objects.
The associated value is a string
NotImplementedError Derived from RuntimeError. In user defined base classes, abstract methods raise this exception when they require derived classes to override the method, or while the class is being developed to indicate that the real implementation still needs to be added. Not used to indicate that an operator or method is not meant to be supported, in that case either leave the operator / method undefined or, if a subclass, set it to None. NotImplementedError and NotImplemented are not interchangeable.
OSError([arg])    OSError(errno, strerror, filename)
   OSError(errno, strerror [, filename[, winerror[, filename2]]])
A system function returned an error, including I/O failures such as file not found or disk full.
Not for illegal argument types or other incidental errors. The three arguments form the args attribute contains only a 2-tuple of the first two constructor arguments. The long form of the constructor sets the corresponding attributes which default to 'None'.
The constructor may return a subclass of OSError. When constructing OSError directly or via an alias, and is not inherited when subclassing.
errno numeric error code
winerror
Under Windows, the native Windows error code. The errno is a similar POSIX code. if winerror is an integer, the errno attribute is determined from the Windows error code, and errno is ignored.
On non-windows platforms, winerror is ignored and does not exist.
strerror The error message provided by the operating system.
filename, filename2

   EnvironmentError aliases of OSError
   IOError aliases of OSError
RecursionError the maximum recursion depth (see sys.getrecursionlimit()) is exceeded. derived from RuntimeError.
ReferenceError a weak reference proxy, created by weakref.proxy() , is used to access an attribute of the referent after it has been garbage collected. For more information on weak references, see the weakref module.
RuntimeError
StopIteration next() and an iterator's __next__() method to signal that there are no further items produced by the iterator. The exception object has an attribute value, which is given as an argument when constructing the exception, and defaults to None.

When a generator or coroutine function returns, a new StopIteration instance is raised, and the value returned by the function is used as the value parameter to the constructor of the exception.

If a generator code directly or indirectly raises code> StopIteration, it is converted into a RuntimeError (retaining the StopIteration as the new exception's cause).

Added value attribute and the ability for generator functions to use it to return a value. Introduced the RuntimeError transformation via from __future__ import generator_stop, see PEP 479.
Enable PEP 479 for all code by default: a StopIteration error raised in a generator is transformed into a RuntimeError .

StopAsyncIteration Must be raised by __anext__() method of an asynchronous iterator object to stop the iteration.
SyntaxError(message, details) Prarser encounterd a syntax error. This may occur in an import statement, a call to the compile(), exec(), or eval(), or when reading the initial script or standard input (also interactively).

The str() of the exception instance returns only the error message. Details is a tuple whose members are also available as separate attributes.
filename  
lineno 1-indexed
offset 1-indexed
text  
end_lineno 1-indexed
end_offset where the error occurred finishes. 1-indexed

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 fBad {a b} field results in this args attribute: (f-string: , (, 1, 2, (a b)n, 1, 5)).

subclasses
    IndentationError Base class for syntax errors related to incorrect indentation.
    TabError indentation contains an inconsistent use of tabs and spaces.
SystemError issue is considered a warning. The associated value is a string
SystemExit sys.exit() inherits from BaseException not Exception so that it is not caught by code that catches Exception.
This allows the exception to properly propagate up and cause python to exit.
When not handled, Python exits; no stack traceback is output.
The constructor accepts the same optional argument passed to sys.exit() .
'None' the exit status is 0;
An integer specifies the system exit status (passed to exit() ).
A string is output and the exit status is 1.

Treated as exception so that clean-up handlers ( finally clauses of try: statements) can be executed, and a debugger can execute a script.
os._exit() exits immediately (for example, in the child process after a call to os.fork()). The exit status or error message that is passed to the constructor. (Defaults to None.)

TypeError Operation or function is applied to an object of wrong type. The associated value is a string.
May be raised by user code to indicate that an attempted operation on an object is not supported, and is not meant to be. An object is meant to support a given operation but has not yet provided an implementation, NotImplementedError should be raised.
Passing arguments of the wrong type (e.g. passing a list when an int is expected) should result in a TypeError ,
passing arguments with the wrong value (e.g. a number outside expected boundaries) should result in a ValueError .
UnicodeError A Unicode-related encoding or decoding error , subclass of ValueError .
UnicodeError has attributes that describe the encoding or decoding error.
For example, err.object[err.start:err.end]
encoding name of the encoding that raised the error.
reason string describing the specific codec error.
object object the codec was attempting to encode or decode.
start first index of invalid data in object.
end index after the last invalid data in object.

subclasses
UnicodeEncodeError Unicode-related error occurs during encoding.
UnicodeDecodeError Unicode-related error occurs during decoding.
UnicodeTranslateError Unicode-related error occurs during translating.

WindowsError Only available on MSWindows.

OS exceptions

subclasses of OSError , raised depending on the system error code.
BlockingIOError an operation would block on an object (e.g. socket) set for non-blocking operation. Corresponds to EAGAIN, EALREADY, EWOULDBLOCK and EINPROGRESS. Can have : characters_written An integer number of characters written to the stream before it blocked. This attribute is available when using the buffered I/O classes from the io module.
ChildProcessError an operation on a child process failed. Corresponds to ECHILD.
ConnectionError Base class for connection-related issues.
subclasses
   ConnectionAbortedError Corresponds to ECONNABORTED.
   ConnectionRefusedError Corresponds to ECONNREFUSED.
   ConnectionResetError Corresponds to ECONNRESET.
   BrokenPipeError 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 to EPIPE and ESHUTDOWN.
FileExistsError trying to create a file or directory which already exists. Corresponds to EEXIST.
FileNotFoundError a file or directory is requested but doesn't exist. Corresponds to ENOENT.
InterruptedError a system call is interrupted by an incoming signal. Corresponds to EINTR. 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.
IsADirectoryError file operation (such as os.remove(arg)) requested on a directory. Corresponds to EISDIR.
NotADirectoryError Directory operation (such as os.listdir(arg)) requested on something which is not a directory.
On most POSIX platforms, it may also be raised if an operation attempts to open or traverse a non-directory file as if it were a directory. Corresponds to ENOTDIR.
PermissionError trying to run an operation without the adequate access rights - for example filesystem permissions. Corresponds to EACCES and EPERM.
ProcessLookupError process doesn't exist. Corresponds to ESRCH.
TimeoutError a system function timed out at the system level. Corresponds to ETIMEDOUT.
See also PEP 3151 - Reworking the OS and IO exception hierarchy
Warning base classes These exceptions are used as warning categories; see the Warning Categories documentation
Warning all categories.
BytesWarning related to bytes and bytearray.
UserWarning generated by user code.
SyntaxWarning dubious syntax.
RuntimeWarning dubious runtime behavior.
ImportWarning probable mistakes in module imports.
Ignored by the default warning filters. Enabling the Python Development Mode shows this warning.
UnicodeWarning Unicode.
EncodingWarning encodings. See Opt-in EncodingWarning for details.
ResourceWarning resource usage. Ignored by the default warning filters. Enabling the Python Development Mode shows this warning.
FutureWarning deprecated features when those warnings are intended for end users of applications that are written in Python.
PendingDeprecationWarning features which are obsolete and expected to be deprecated in the future, but are not deprecated at the moment. rarely used as emitting a warning about a possible upcoming deprecation is unusual, and DeprecationWarning is preferred for active deprecations.
Ignored by the default warning filters. Enabling the Python Development Mode shows this warning.
DeprecationWarning deprecated features when those warnings are intended for Python developers. Ignored by the default warning filters, except in the __main__ module (PEP 565). Enabling the Python Development Mode shows this warning. The deprecation policy is described in PEP 387.

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

table of Contents

Built-in Exceptions
Exception context
Inheriting from built-in exceptions
Base classes
Concrete exceptions
OS exceptions Warnings
Exception hierarchy
Previous topic
Built-in Types

import errno

>> errno.EIO
5
>> errno.NO_DATA
211

__class__ __name__ errorcode
EACCES EADDRINUSE EAGAIN EALREADY EBADF ECONNABORTED ECONNREFUSED ECONNRESET EEXIST EHOSTUNREACH EINPROGRESS EINVAL EIO EISDIR EMSGSIZE ENETDOWN ENOBUFS ENODEV ENOENT ENOMEM ENOTCONN EOPNOTSUPP EPERM ETIMEDOUT ERRMEM ERRBUF ERRTIMEOUT ERRRTE ERRINPROGRESS ERRVAL ERRWOULDBLOCK ERRUSE ERRALREADY ERRISCONN ERRABRT ERRRST ERRCLSD ERRCONN ERRARG ERRIF HOST_NOT_FOUND NO_DATA NO_RECOVERY TRY_AGAIN
EAI
Socket extensions for IPv6 netdb.h
SB-BSD-SOCKETS-INTERNAL
EAIFAIL EAIMEMORY EAIFAMILY EAISERVICE EAINONAME
MBEDTLS_ERR_NET_
Mbed TLS is a C library that implements cryptographic primitives, X.509 certificate manipulation and the SSL/TLS and DTLS protocols
EPS_ERR_NO_MEM EPS_ERR_INVALID_ARG EPS_ERR_INVALID_STATE EPS_ERR_INVALID_SIZE EPS_ERR_NOT_FOUND EPS_ERR_NOT_SUPPORTED EPS_ERR_TIMEOUT EPS_ERR_INVALID_RESPONSE EPS_ERR_INVALID_CRC EPS_ERR_INVALID_VERSION EPS_ERR_INVALID_MAC
SOCKET_FAILED CONNECT_FAILED BIND_FAILED LISTEN_FAILED ACCEPT_FAILED RECV_FAILED SEND_FAILED POLL_FAILED
UNKNOWN_HOST CONN_RESET BUFFER_TOO_SMALL INVALID_CONTEXT BAD_INPUT_DATA
MBEDTLS_ERR_SSL_
INVALID_MAC INVALID_RECORD CONN_EOF PEER_VERIFY_FAILED PEER_CLOSE_NOTIFY UNKNOWN_CIPHER NO_CIPHER_CHOSEN NO_USABLE_CIPHERSUITE NO_RNG PRIVATE_KEY_REQUIRED PK_TYPE_MISMATCH HELLO_VERIFY_REQUIRED BAD_HS_CLIENT_HELLO BAD_HS_SERVER_HELLO BAD_HS_SERVER_HELLO_DONE WAITING_SERVER_HELLO_RENEGO BAD_HS_PROTOCOL_VERSION BAD_HS_NEW_SESSION_TICKET CA_CHAIN_REQUIRED CERTIFICATE_REQUIRED BAD_HS_CERTIFICATE BAD_HS_CERTIFICATE_REQUEST BAD_HS_CERTIFICATE_VERIFY CERTIFICATE_TOO_LARGE NO_CLIENT_CERTIFICATE BAD_HS_SERVER_KEY_EXCHANGE BAD_HS_CLIENT_KEY_EXCHANGE BAD_HS_CLIENT_KEY_EXCHANGE_RP BAD_HS_CLIENT_KEY_EXCHANGE_CS BAD_HS_CHANGE_CIPHER_SPEC BAD_HS_FINISHED ALLOC_FAILED HW_ACCEL_FAILED HW_ACCEL_FALLTHROUGH COMPRESSION_FAILED SESSION_TICKET_EXPIRED UNKNOWN_IDENTITY WANT_READ WANT_WRITE CLIENT_RECONNECT INVALID_VERIFY_HASH CONTINUE_PROCESSING ASYNC_IN_PROGRESS TIMEOUT COUNTER_WRAPPING BUFFER_TOO_SMALL UNEXPECTED_MESSAGE FATAL_ALERT_MESSAGE UNEXPECTED_RECORD NON_FATAL FEATURE_UNAVAILABLE BAD_INPUT_DATA INTERNAL_ERROR
MBEDTLS_ERR_PK_
ALLOC_FAILED TYPE_MISMATCH BAD_INPUT_DATA FILE_IO_ERROR KEY_INVALID_VERSION KEY_INVALID_FORMAT UNKNOWN_PK_ALG PASSWORD_REQUIRED PASSWORD_MISMATCH INVALID_PUBKEY INVALID_ALG UNKNOWN_NAMED_CURVE FEATURE_UNAVAILABLE SIG_LEN_MISMATCH HW_ACCEL_FAILED

Docs.Python

try:, except, finally: with exception handling. Calls __enter__(self) lastly calls __exit__(self) . geeksForGeeks