Exceptions
##########

.. _handling_python_exceptions_sv:

Handling exceptions from Python in SystemVerilog
================================================

When SystemVerilog calls Python functions, such as in a callback function or when
manipulating Python objects, and Python raises an ``Exception``, PyStim
converts the Python exception into a SystemVerilog error of type
:class:`pystim_pkg::py_error` whose payload contains a SV string textual
summary and the actual Python exception. To get textual summary of the Python
exception, use the :func:`to_string` method of the :class:`pystim_pkg::py_error` object.

.. tabularcolumns:: |p{0.5\textwidth}|p{0.45\textwidth}|

+--------------------------------------+--------------------------------------+
|  Exception raised in Python          |  Thrown as SV error type             |
+======================================+======================================+
| Any Python ``Exception``             | :class:`pystim_pkg::py_error`        |
+--------------------------------------+--------------------------------------+

For example:

.. code-block:: systemverilog

    begin
        // open("missing.txt", "r")
        py_object file = py_module::import_("io").attr("open").call(py::str_("missing.txt"), py::str_("r"));
        py_object text;
        if(file.is_ok())begin
            text = file.attr("read").call();
            void ' (file.attr("close").call());
            text.delete();
            file.delete();
        end else begin
            // Handle the exception
            // FileNotFoundError: [Errno 2] No such file or directory: 'missing.txt'
            $display("Error: %s", file.to_string());
        end 
    end








