Search code examples
quarto

How can I force an error in code without stoping the execution in quarto?


I'm creating a document for students using quarto. One of the things I want to teach is how to read and understand error messages, so I was planning in creating wrong code blocks to force certain error messages (like the one below):

a_list = [1,2,"a"]
a_list[3]
# I want to generate an error to explain that python starts counting at 0

Regretfully, when I write the code above, quarto complains (with good reason) and will stop executing the rest of the code blocks and rendering the file.

Is there a way to get the error message while not stoping the execution?

I thought something like this would work, but it doesnt:

# | error: true
a_list[3]

Solution

  • The following works for me:

    ---
    title: test-error
    ---    
    
    ```{python}
    #| error: true
    a_list = [1,2,"a"]
    a_list[3]
    ```
    

    It produces the following output:

    The output generated by the snippet above, including "Index Error: list index out of range"

    One thing to make sure is that the #| error: true line is at the beginning of the cell, and that there's no spaces between # and |.

    You can also enable this behaviour across the whole document in the yaml header, like so:

    ---
    title: test-error
    execute:
      error: true
    ---    
    
    ```{python}
    a_list = [1,2,"a"]
    a_list[3]
    ```
    
    ```{r}
    stop("Another error that could stop my .qmd from evaluating")
    ```