Skip to content

Reader/Writer runtime exceptions could be more useful #265

@naegelejd

Description

@naegelejd

Currently, exceptions in the generated code are all thrown as runtime errors (RuntimeError in python, std::runtime_error in c++). For example, when reading a binary stream:

if magic_bytes != MAGIC_BYTES: # pyright: ignore [reportUnnecessaryComparison]
raise RuntimeError("Invalid magic bytes")
version = read_fixed_int32(self._stream)
if version != CURRENT_BINARY_FORMAT_VERSION:
raise RuntimeError("Invalid binary format version")
self._schema = string_serializer.read(self._stream)
if expected_schema and self._schema != expected_schema:
raise RuntimeError("Invalid schema")

These would be more useful if they were library-defined exceptions.

For example, using mrd, if someone attempts to use a mrd.BinaryReader to open an invalid file in Python, the user will see the following:

Traceback (most recent call last):
  ...
    with mrd.BinaryMrdReader(args.input_file) as reader:
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/uv/.venv/lib/python3.12/site-packages/mrd/binary.py", line 49, in __init__
    _binary.BinaryProtocolReader.__init__(self, stream, MrdReaderBase.schema)
  File "/opt/uv/.venv/lib/python3.12/site-packages/mrd/_binary.py", line 81, in __init__
    raise RuntimeError("Invalid magic bytes")
RuntimeError: Invalid magic bytes

Instead, the Python program that opens the binary reader could catch a mrd.InvalidMagicBytes exception, and print a helfpul error message, such as "Invalid file, are you sure it is in MRD format?"...

I vote we replace these runtime errors with custom exceptions that can be better handled downstream. This applies to the generated C++ and MATLAB code as well.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions