Handling Exceptions

This article explains how to properly handle exceptions when using Zivid Motion in both Python and C++.

Python Exception Handling

In Python, exceptions from the Zivid Motion library are handled automatically by the language runtime. Nested exceptions are properly unwrapped, and you can catch them using standard Python exception handling:

# ...

try:
    result = planner.path(...)

except Exception as e:
    print(f"An error occurred: {e}")

Python automatically handles nested exceptions in the traceback, so you don’t need to do anything special to see the full exception chain.

C++ Exception Handling

In C++, exceptions may be nested to provide more context about what went wrong. Zivid Motion uses nested exceptions to chain related errors together. To properly handle these exceptions, you need to explicitly unwrap the nested exception chain.

With Zivid SDK Installed

If you have access to the Zivid SDK, you can use the Zivid::toString(const std::exception&) function, which automatically handles nested exceptions for you:

#include <Zivid/Exception.h>
#include <Zivid/Motion/Planner.h>

#include <iostream>

int main()
{
    // ...

    try
    {
        auto result = planner.path(...);
    }
    catch(const std::exception &e)
    {
        std::cerr << "Error: " << Zivid::toString(e) << std::endl;
    }
}

The Zivid::toString() function will format the exception message along with any nested exceptions, making it easy to understand the full context of what went wrong.

Without Zivid SDK Installed

If you don’t have access to the Zivid SDK (for example, in a standalone Zivid Motion application), you need to manually handle nested exceptions:

#include <Zivid/Motion/Planner.h>

#include <iostream>
#include <exception>

void printException(const std::exception &e, const int level = 0)
{
    std::cerr << std::string(level * 4, ' ') << (level ? "+ " : "") << "Exception: " << e.what() << '\n';
    try
    {
        std::rethrow_if_nested(e);
    }
    catch(const std::exception &nestedException)
    {
        printException(nestedException, level + 1);
    }
    catch(...)
    {}
}

int main()
{
    // ...

    try
    {
        auto result = planner.path(...);
    }
    catch(const std::exception &exception)
    {
        printException(exception);
    }
}

This approach using the printException helper function recursively unwraps nested exceptions and prints them with proper indentation, showing the full chain of errors that led to the failure.