Exceptions and error codes

List of all exceptions

This section lists all available exceptions in alphabetical order.

class ArithmeticError

The base class for those built-in exceptions that are raised for various arithmetic errors.

class AssertionError

Raised when an assert statement fails.

class AttributeError

Raised when an attribute reference or assignment fails.

class BaseException

The base class for all built-in exceptions.

It is not meant to be directly inherited by user-defined classes (for that, use Exception).

class EOFError

Raised when the input() function hits an end-of-file condition (EOF) without reading any data.

class Exception

All built-in exceptions are derived from this class.

All user-defined exceptions should also be derived from this class.

class GeneratorExit

Raised when a generator or coroutine is closed.

class ImportError

Raised when the import statement is unable to load a module.

class IndentationError

Base class for syntax errors related to incorrect indentation.

class IndexError

Raised when a sequence subscript is out of range.

class KeyboardInterrupt

Raised when the user hits the interrupt key (normally Control-C).

class KeyError

Raised when a mapping (dictionary) key is not found in the set of existing keys.

class LookupError

The base class for the exceptions that are raised when a key or index used on a mapping or sequence is invalid.

class MemoryError

Raised when an operation runs out of memory.

class NameError

Raised when a local or global name is not found.

class NotImplementedError

In user defined base classes, abstract methods should 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.

class OSError

This exception is raised by the firmware, which is the Operating System that runs on the hub. For example, it raises an OSError if you call Motor(Port.A) when there is no motor on port A.

See the OSError section for additional details.

errno: int

Specifies which kind of OSError occurred, as listed here.

class OverflowError

Raised when the result of an arithmetic operation is too large to be represented.

class 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.

class 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.

Generator functions should return instead of raising this directly.

class SyntaxError

Raised when the parser encounters a syntax error.

class SystemExit

Raised when you press the stop button on the hub or in the Pybricks Code app.

class TypeError

Raised when an operation or function is applied to an object of inappropriate type.

class ValueError

Raised when an operation or function receives an argument that has the right type but an inappropriate value. This is used when the situation is not described by a more precise exception such as IndexError.

class ZeroDivisionError

Raised when the second argument of a division or modulo operation is zero.

Using OSError with uerrno

The errno attribute of an OSError indicates why the exception was raised. This attribute has one of the following values, which can be imported from the uerrno module. See also this example.

EAGAIN: int

The operation is not complete and should be tried again soon.

EBUSY: int

The device or resource is busy and cannot be used right now.

ECANCELED: int

The operation was canceled.

EINVAL: int

An invalid argument was given. Usually ValueError is used instead.

EIO: int

An unspecified error occurred.

ENODEV: int

Device was not found. For example, a sensor or motor is not plugged in the correct port.

EOPNOTSUPP: int

The operation is not supported on this hub or on the connected device.

EPERM: int

The operation cannot be performed in the current state.

ETIMEDOUT: int

The operation timed out.

errorcode: Dict[int, str]

Dictionary that maps numeric error codes to strings with symbolic error code.

Examples

Debugging in the REPL terminal

from pybricks.pupdevices import Motor
from pybricks.parameters import Port
from pybricks.tools import wait

# Initialize the motor.
test_motor = Motor(Port.A)

# Start moving at 500 deg/s.
test_motor.run(500)

# If you click on the terminal window and press CTRL+C,
# you can continue debugging in this terminal.
wait(5000)

# You can also do this to exit the script and enter the
# terminal. Variables in the global scope are still available.
raise KeyboardInterrupt

# For example, you can copy the following line to the terminal
# to get the angle, because test_motor is still available.
test_motor.angle()

Running code when the stop button is pressed

from pybricks.tools import wait

print("Started!")

try:

    # Run your script here as you normally would. In this
    # example we just wait forever and do nothing.
    while True:
        wait(1000)

except SystemExit:
    # This code will run when you press the stop button.
    # This can be useful to "clean up", such as to move
    # the motors back to their starting positions.
    print("You pressed the stop button!")

Detecting devices using OSError

from pybricks.pupdevices import Motor
from pybricks.parameters import Port

from uerrno import ENODEV

try:
    # Try to initialize a motor.
    my_motor = Motor(Port.A)

    # If all goes well, you'll see this message.
    print("Detected a motor.")
except OSError as ex:
    # If an OSError was raised, we can check what
    # kind of error this was, like ENODEV.
    if ex.errno == ENODEV:
        # ENODEV is short for "Error, no device."
        print("There is no motor this port.")
    else:
        print("Another error occurred.")