microsoft / microsoft/onnxruntime

[Feature Request] Define a Python exception hierarchy

Open
#13,924 0 comments 0 reactions 0 assignees View on GitHub
feature request
Dominant language
C++
Stars
21.9k
Forks
4.2k
Avg merge
4d 11h
Merged PRs (30d)
184

Description

### Describe the feature request

All C++ exceptions are translated to Python exceptions whose base class is [`Exception`](https://docs.python.org/3/library/exceptions.html#Exception). This is inconvenient because catching `onnxruntime` specific exceptions is not easy or very cumbersone and error prone.

An `onnxruntime` specific base class, say `onnxruntime.Error` should be defined to explicitly contruct an `onnxruntime` exception hierarcy.

### Describe scenario use case

Currently to catch exceptions raised by onnxruntime one has to write
```
try:
...
except Exception as exc:
...
```
ad inspect `exc` and re-raise it if it not a `onnxruntime` exception.

A second approach is to be more explicit and verbose:
```
from onnxruntime.capi.onnxruntime_pybind11_state import (
EPFail,
EngineError,
Fail,
InvalidArgument,
InvalidGraph,
InvalidProtobuf,
ModelLoaded,
NoModel,
NoSuchFile,
NotImplemented,
RuntimeException,
)

try:
...
except (
EPFail,
EngineError,
Fail,
InvalidArgument,
InvalidGraph,
InvalidProtobuf,
ModelLoaded,
NoModel,
NoSuchFile,
NotImplemented,
RuntimeException,
) as exc:
...
```

If an explicit onnxruntime exception hierarcy is defined, this could simply be
```
import onnxruntime

try:
...
except onnxruntime.Error as exc:
...
```

A quick check to the `pybind11` [Exceptions docs](https://pybind11.readthedocs.io/en/stable/advanced/exceptions.html?highlight=exceptions#exceptions) shows that it should be quite straightforward to implement this feature.

Contributor guide

Open the contributing guide

Research direction

Start with the Python exception classes in onnxruntime.capi.onnxruntime_pybind11_state and the pybind11 exceptions documentation linked in the issue. Trace how the listed C++ exceptions are exposed to Python and determine where the proposed onnxruntime.Error base class should be defined. Done means callers can catch translated onnxruntime exceptions through onnxruntime.Error while retaining the specific exception types.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp, python
Domain
api, machine-learning
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.