
.. DO NOT EDIT.
.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY.
.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE:
.. "examples/advanced/error_handling.py"
.. LINE NUMBERS ARE GIVEN BELOW.

.. only:: html

    .. note::
        :class: sphx-glr-download-link-note

        Click :ref:`here <sphx_glr_download_examples_advanced_error_handling.py>`
        to download the full example code

.. rst-class:: sphx-glr-example-title

.. _sphx_glr_examples_advanced_error_handling.py:


Error handling using an interactive parser
==========================================

This example demonstrates error handling using an interactive parser in LALR

When the parser encounters an UnexpectedToken exception, it creates a
an interactive parser with the current parse-state, and lets you control how
to proceed step-by-step. When you've achieved the correct parse-state,
you can resume the run by returning True.

.. GENERATED FROM PYTHON SOURCE LINES 12-38

.. code-block:: default


    from lark import Token

    from examples.advanced._json_parser import json_parser

    def ignore_errors(e):
        if e.token.type == 'COMMA':
            # Skip comma
            return True
        elif e.token.type == 'SIGNED_NUMBER':
            # Try to feed a comma and retry the number
            e.interactive_parser.feed_token(Token('COMMA', ','))
            e.interactive_parser.feed_token(e.token)
            return True

        # Unhandled error. Will stop parse and raise exception
        return False


    def main():
        s = "[0 1, 2,, 3,,, 4, 5 6 ]"
        res = json_parser.parse(s, on_error=ignore_errors)
        print(res)      # prints [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0]

    main()



.. rst-class:: sphx-glr-timing

   **Total running time of the script:** ( 0 minutes  0.000 seconds)


.. _sphx_glr_download_examples_advanced_error_handling.py:


.. only :: html

 .. container:: sphx-glr-footer
    :class: sphx-glr-footer-example



  .. container:: sphx-glr-download sphx-glr-download-python

     :download:`Download Python source code: error_handling.py <error_handling.py>`



  .. container:: sphx-glr-download sphx-glr-download-jupyter

     :download:`Download Jupyter notebook: error_handling.ipynb <error_handling.ipynb>`


.. only:: html

 .. rst-class:: sphx-glr-signature

    `Gallery generated by Sphinx-Gallery <https://sphinx-gallery.github.io>`_
