Exceptions

All of the exceptions raised from PyNaCl-exposed methods/functions are subclasses of nacl.exceptions.CryptoError. This means downstream users can just wrap cryptographic operations inside a

try:
    # cryptographic operations
except nacl.exceptions.CryptoError:
    # cleanup after any kind of exception
    # raised from cryptographic-related operations

These are the exceptions implemented in nacl.exceptions:

PyNaCl specific exceptions

class nacl.exceptions.CryptoError[source]

Base exception for all nacl related errors

class nacl.exceptions.BadSignatureError[source]

Raised when the signature was forged or otherwise corrupt.

class nacl.exceptions.InvalidkeyError[source]

Raised on password/key verification mismatch

class nacl.exceptions.UnavailableError[source]

is a subclass of RuntimeError, raised when trying to call functions not available in a minimal build of libsodium.

PyNaCl exceptions mixing-in standard library ones

Both for clarity and for compatibility with previous releases of the PyNaCl, the following exceptions mix-in the same-named standard library exception to CryptoError.

class nacl.exceptions.RuntimeError[source]

is a subclass of both CryptoError and standard library’s RuntimeError, raised for internal library errors

class nacl.exceptions.AssertionError[source]

is a subclass of both CryptoError and standard library’s AssertionError, raised by default from ensure() when the checked condition is False

class nacl.exceptions.TypeError[source]

is a subclass of both CryptoError and standard library’s TypeError

class nacl.exceptions.ValueError[source]

is a subclass of both CryptoError and standard library’s ValueError

Utility functions for exception handling

nacl.exceptions.ensure(cond, *args, raising=nacl.exceptions.AssertionError)[source]

Returns if a condition is true, otherwise raise a caller-configurable Exception

Parameters
  • cond (bool) – the condition to be checked

  • args (sequence) – the arguments to be passed to the exception’s constructor

  • raising (exception) – the exception to be raised if cond is False

Example usage:

nacl.exceptions.ensure(
    a == 1 or a == 2,
    "a must be either 1 or 2"
)