{ "cells": [ { "cell_type": "markdown", "metadata": { "button": false, "new_sheet": false, "run_control": { "read_only": false }, "slideshow": { "slide_type": "slide" } }, "source": [ "# Error Handling\n", "\n", "The code in this notebook helps with handling errors. Normally, an error in notebook code causes the execution of the code to stop; while an infinite loop in notebook code causes the notebook to run without end. This notebook provides two classes to help address these concerns." ] }, { "cell_type": "markdown", "metadata": { "button": false, "new_sheet": false, "run_control": { "read_only": false }, "slideshow": { "slide_type": "subslide" } }, "source": [ "**Prerequisites**\n", "\n", "* This notebook needs some understanding on advanced concepts in Python, notably \n", " * classes\n", " * the Python `with` statement\n", " * tracing\n", " * measuring time\n", " * exceptions" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Synopsis\n", "\n", "\n", "To [use the code provided in this chapter](Importing.ipynb), write\n", "\n", "```python\n", ">>> from fuzzingbook.ExpectError import \n", "```\n", "\n", "and then make use of the following features.\n", "\n", "\n", "The `ExpectError` class allows you to catch and report exceptions, yet resume execution. This is useful in notebooks, as they would normally interrupt execution as soon as an exception is raised. Its typical usage is in conjunction with a `with` clause:\n", "\n", "```python\n", ">>> with ExpectError():\n", ">>> x = 1 / 0\n", "Traceback (most recent call last):\n", " File \"/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_82852/2664980466.py\", line 2, in \n", " x = 1 / 0\n", "ZeroDivisionError: division by zero (expected)\n", "\n", "```\n", "The `ExpectTimeout` class allows you to interrupt execution after the specified time. This is useful for interrupting code that might otherwise run forever.\n", "\n", "```python\n", ">>> with ExpectTimeout(5):\n", ">>> long_running_test()\n", "Start\n", "0 seconds have passed\n", "1 seconds have passed\n", "2 seconds have passed\n", "3 seconds have passed\n", "\n", "Traceback (most recent call last):\n", " File \"/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_82852/1223755941.py\", line 2, in \n", " long_running_test()\n", " File \"/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_82852/3930412460.py\", line 4, in long_running_test\n", " time.sleep(1)\n", " File \"/Users/zeller/Projects/fuzzingbook/notebooks/Timeout.ipynb\", line 43, in timeout_handler\n", " raise TimeoutError()\n", "TimeoutError (expected)\n", "\n", "```\n", "The exception and the associated traceback are printed as error messages. If you do not want that, \n", "use these keyword options:\n", "\n", "* `print_traceback` (default True) can be set to `False` to avoid the traceback being printed\n", "* `mute` (default False) can be set to `True` to completely avoid any output.\n", "\n" ] }, { "cell_type": "markdown", "metadata": { "button": false, "new_sheet": false, "run_control": { "read_only": false }, "slideshow": { "slide_type": "slide" } }, "source": [ "## Catching Errors\n", "\n", "The class `ExpectError` allows to express that some code produces an exception. A typical usage looks as follows:\n", "\n", "```Python\n", "from ExpectError import ExpectError\n", "\n", "with ExpectError():\n", " function_that_is_supposed_to_fail()\n", "```\n", "\n", "If an exception occurs, it is printed on standard error; yet, execution continues." ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "button": false, "execution": { "iopub.execute_input": "2024-01-18T17:30:53.963222Z", "iopub.status.busy": "2024-01-18T17:30:53.962878Z", "iopub.status.idle": "2024-01-18T17:30:54.010591Z", "shell.execute_reply": "2024-01-18T17:30:54.010253Z" }, "new_sheet": false, "run_control": { "read_only": false }, "slideshow": { "slide_type": "skip" } }, "outputs": [], "source": [ "import bookutils.setup" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "button": false, "execution": { "iopub.execute_input": "2024-01-18T17:30:54.012408Z", "iopub.status.busy": "2024-01-18T17:30:54.012263Z", "iopub.status.idle": "2024-01-18T17:30:54.014054Z", "shell.execute_reply": "2024-01-18T17:30:54.013773Z" }, "new_sheet": false, "run_control": { "read_only": false }, "slideshow": { "slide_type": "skip" } }, "outputs": [], "source": [ "import traceback\n", "import sys" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "execution": { "iopub.execute_input": "2024-01-18T17:30:54.015445Z", "iopub.status.busy": "2024-01-18T17:30:54.015353Z", "iopub.status.idle": "2024-01-18T17:30:54.017143Z", "shell.execute_reply": "2024-01-18T17:30:54.016861Z" }, "slideshow": { "slide_type": "skip" } }, "outputs": [], "source": [ "from types import FrameType, TracebackType" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "execution": { "iopub.execute_input": "2024-01-18T17:30:54.018591Z", "iopub.status.busy": "2024-01-18T17:30:54.018473Z", "iopub.status.idle": "2024-01-18T17:30:54.020127Z", "shell.execute_reply": "2024-01-18T17:30:54.019863Z" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [], "source": [ "# ignore\n", "from typing import Union, Optional, Callable, Any" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "button": false, "execution": { "iopub.execute_input": "2024-01-18T17:30:54.021841Z", "iopub.status.busy": "2024-01-18T17:30:54.021528Z", "iopub.status.idle": "2024-01-18T17:30:54.025531Z", "shell.execute_reply": "2024-01-18T17:30:54.024977Z" }, "new_sheet": false, "run_control": { "read_only": false }, "slideshow": { "slide_type": "subslide" } }, "outputs": [], "source": [ "class ExpectError:\n", " \"\"\"Execute a code block expecting (and catching) an error.\"\"\"\n", "\n", " def __init__(self, exc_type: Optional[type] = None, \n", " print_traceback: bool = True, mute: bool = False):\n", " \"\"\"\n", " Constructor. Expect an exception of type `exc_type` (`None`: any exception).\n", " If `print_traceback` is set (default), print a traceback to stderr.\n", " If `mute` is set (default: False), do not print anything.\n", " \"\"\"\n", " self.print_traceback = print_traceback\n", " self.mute = mute\n", " self.expected_exc_type = exc_type\n", "\n", " def __enter__(self) -> Any:\n", " \"\"\"Begin of `with` block\"\"\"\n", " return self\n", "\n", " def __exit__(self, exc_type: type, \n", " exc_value: BaseException, tb: TracebackType) -> Optional[bool]:\n", " \"\"\"End of `with` block\"\"\"\n", " if exc_type is None:\n", " # No exception\n", " return\n", "\n", " if (self.expected_exc_type is not None\n", " and exc_type != self.expected_exc_type):\n", " raise # Unexpected exception\n", "\n", " # An exception occurred\n", " if self.print_traceback:\n", " lines = ''.join(\n", " traceback.format_exception(\n", " exc_type,\n", " exc_value,\n", " tb)).strip()\n", " else:\n", " lines = traceback.format_exception_only(\n", " exc_type, exc_value)[-1].strip()\n", "\n", " if not self.mute:\n", " print(lines, \"(expected)\", file=sys.stderr)\n", " return True # Ignore it" ] }, { "cell_type": "markdown", "metadata": { "button": false, "new_sheet": false, "run_control": { "read_only": false }, "slideshow": { "slide_type": "subslide" } }, "source": [ "Here's an example:" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "button": false, "execution": { "iopub.execute_input": "2024-01-18T17:30:54.027697Z", "iopub.status.busy": "2024-01-18T17:30:54.027589Z", "iopub.status.idle": "2024-01-18T17:30:54.029707Z", "shell.execute_reply": "2024-01-18T17:30:54.029349Z" }, "new_sheet": false, "run_control": { "read_only": false }, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "def fail_test() -> None:\n", " # Trigger an exception\n", " x = 1 / 0" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "button": false, "execution": { "iopub.execute_input": "2024-01-18T17:30:54.031694Z", "iopub.status.busy": "2024-01-18T17:30:54.031529Z", "iopub.status.idle": "2024-01-18T17:30:54.033895Z", "shell.execute_reply": "2024-01-18T17:30:54.033578Z" }, "new_sheet": false, "run_control": { "read_only": false }, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "Traceback (most recent call last):\n", " File \"/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_82852/1235320646.py\", line 2, in \n", " fail_test()\n", " File \"/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_82852/278441162.py\", line 3, in fail_test\n", " x = 1 / 0\n", "ZeroDivisionError: division by zero (expected)\n" ] } ], "source": [ "with ExpectError():\n", " fail_test()" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "button": false, "execution": { "iopub.execute_input": "2024-01-18T17:30:54.056923Z", "iopub.status.busy": "2024-01-18T17:30:54.056450Z", "iopub.status.idle": "2024-01-18T17:30:54.059191Z", "shell.execute_reply": "2024-01-18T17:30:54.058904Z" }, "new_sheet": false, "run_control": { "read_only": false }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "ZeroDivisionError: division by zero (expected)\n" ] } ], "source": [ "with ExpectError(print_traceback=False):\n", " fail_test()" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "We can specify the type of the expected exception. This way, if something else happens, we will get notified." ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "execution": { "iopub.execute_input": "2024-01-18T17:30:54.060831Z", "iopub.status.busy": "2024-01-18T17:30:54.060717Z", "iopub.status.idle": "2024-01-18T17:30:54.062654Z", "shell.execute_reply": "2024-01-18T17:30:54.062407Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "Traceback (most recent call last):\n", " File \"/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_82852/1259188418.py\", line 2, in \n", " fail_test()\n", " File \"/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_82852/278441162.py\", line 3, in fail_test\n", " x = 1 / 0\n", "ZeroDivisionError: division by zero (expected)\n" ] } ], "source": [ "with ExpectError(ZeroDivisionError):\n", " fail_test()" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "execution": { "iopub.execute_input": "2024-01-18T17:30:54.064212Z", "iopub.status.busy": "2024-01-18T17:30:54.064108Z", "iopub.status.idle": "2024-01-18T17:30:54.066164Z", "shell.execute_reply": "2024-01-18T17:30:54.065891Z" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "Traceback (most recent call last):\n", " File \"/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_82852/2242794116.py\", line 2, in \n", " with ExpectError(ZeroDivisionError):\n", " File \"/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_82852/2242794116.py\", line 3, in \n", " some_nonexisting_function() # type: ignore\n", "NameError: name 'some_nonexisting_function' is not defined (expected)\n" ] } ], "source": [ "with ExpectError():\n", " with ExpectError(ZeroDivisionError):\n", " some_nonexisting_function() # type: ignore" ] }, { "cell_type": "markdown", "metadata": { "button": false, "new_sheet": false, "run_control": { "read_only": false }, "slideshow": { "slide_type": "slide" } }, "source": [ "## Catching Timeouts\n", "\n", "The class `ExpectTimeout(seconds)` allows expressing that some code may run for a long or infinite time; execution is thus interrupted after `seconds` seconds. A typical usage looks as follows:\n", "\n", "```Python\n", "from ExpectError import ExpectTimeout\n", "\n", "with ExpectTimeout(2) as t:\n", " function_that_is_supposed_to_hang()\n", "```\n", "\n", "If an exception occurs, it is printed on standard error (as with `ExpectError`); yet, execution continues.\n", "\n", "Should there be a need to cancel the timeout within the `with` block, `t.cancel()` will do the trick.\n", "\n", "The implementation uses `sys.settrace()`, as this seems to be the most portable way to implement timeouts. It is not very efficient, though. Also, it only works on individual lines of Python code and will not interrupt a long-running system function." ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "button": false, "execution": { "iopub.execute_input": "2024-01-18T17:30:54.067712Z", "iopub.status.busy": "2024-01-18T17:30:54.067589Z", "iopub.status.idle": "2024-01-18T17:30:54.069240Z", "shell.execute_reply": "2024-01-18T17:30:54.068948Z" }, "new_sheet": false, "run_control": { "read_only": false }, "slideshow": { "slide_type": "skip" } }, "outputs": [], "source": [ "import sys\n", "import time" ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "execution": { "iopub.execute_input": "2024-01-18T17:30:54.070777Z", "iopub.status.busy": "2024-01-18T17:30:54.070672Z", "iopub.status.idle": "2024-01-18T17:30:54.094660Z", "shell.execute_reply": "2024-01-18T17:30:54.094206Z" }, "slideshow": { "slide_type": "skip" } }, "outputs": [], "source": [ "from Timeout import Timeout" ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "button": false, "execution": { "iopub.execute_input": "2024-01-18T17:30:54.097522Z", "iopub.status.busy": "2024-01-18T17:30:54.097302Z", "iopub.status.idle": "2024-01-18T17:30:54.101380Z", "shell.execute_reply": "2024-01-18T17:30:54.100937Z" }, "new_sheet": false, "run_control": { "read_only": false }, "slideshow": { "slide_type": "subslide" } }, "outputs": [], "source": [ "class ExpectTimeout(Timeout): # type: ignore\n", " \"\"\"Execute a code block expecting (and catching) a timeout.\"\"\"\n", "\n", " def __init__(self, timeout: Union[int, float],\n", " print_traceback: bool = True, mute: bool = False):\n", " \"\"\"\n", " Constructor. Interrupt execution after `seconds` seconds.\n", " If `print_traceback` is set (default), print a traceback to stderr.\n", " If `mute` is set (default: False), do not print anything.\n", " \"\"\"\n", " super().__init__(timeout)\n", "\n", " self.print_traceback = print_traceback\n", " self.mute = mute\n", "\n", " def __exit__(self, exc_type: type,\n", " exc_value: BaseException, tb: TracebackType) -> Optional[bool]:\n", " \"\"\"End of `with` block\"\"\"\n", "\n", " super().__exit__(exc_type, exc_value, tb)\n", "\n", " if exc_type is None:\n", " return\n", "\n", " # An exception occurred\n", " if self.print_traceback:\n", " lines = ''.join(\n", " traceback.format_exception(\n", " exc_type,\n", " exc_value,\n", " tb)).strip()\n", " else:\n", " lines = traceback.format_exception_only(\n", " exc_type, exc_value)[-1].strip()\n", "\n", " if not self.mute:\n", " print(lines, \"(expected)\", file=sys.stderr)\n", "\n", " return True # Ignore exception" ] }, { "cell_type": "markdown", "metadata": { "button": false, "new_sheet": false, "run_control": { "read_only": false }, "slideshow": { "slide_type": "subslide" } }, "source": [ "Here's an example:" ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "button": false, "execution": { "iopub.execute_input": "2024-01-18T17:30:54.103550Z", "iopub.status.busy": "2024-01-18T17:30:54.103440Z", "iopub.status.idle": "2024-01-18T17:30:54.106057Z", "shell.execute_reply": "2024-01-18T17:30:54.105528Z" }, "new_sheet": false, "run_control": { "read_only": false }, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "def long_running_test() -> None:\n", " print(\"Start\")\n", " for i in range(10):\n", " time.sleep(1)\n", " print(i, \"seconds have passed\")\n", " print(\"End\")" ] }, { "cell_type": "code", "execution_count": 15, "metadata": { "button": false, "execution": { "iopub.execute_input": "2024-01-18T17:30:54.108261Z", "iopub.status.busy": "2024-01-18T17:30:54.108119Z", "iopub.status.idle": "2024-01-18T17:30:59.119947Z", "shell.execute_reply": "2024-01-18T17:30:59.115674Z" }, "new_sheet": false, "run_control": { "read_only": false }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Start\n", "0 seconds have passed\n", "1 seconds have passed\n", "2 seconds have passed\n", "3 seconds have passed\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "TimeoutError (expected)\n" ] } ], "source": [ "with ExpectTimeout(5, print_traceback=False):\n", " long_running_test()" ] }, { "cell_type": "markdown", "metadata": { "button": false, "new_sheet": false, "run_control": { "read_only": false }, "slideshow": { "slide_type": "fragment" } }, "source": [ "Note that it is possible to nest multiple timeouts." ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "button": false, "execution": { "iopub.execute_input": "2024-01-18T17:30:59.131519Z", "iopub.status.busy": "2024-01-18T17:30:59.130771Z", "iopub.status.idle": "2024-01-18T17:31:07.152712Z", "shell.execute_reply": "2024-01-18T17:31:07.150536Z" }, "new_sheet": false, "run_control": { "read_only": false }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Start\n", "0 seconds have passed\n", "1 seconds have passed\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "TimeoutError (expected)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Start\n", "0 seconds have passed\n", "1 seconds have passed\n", "2 seconds have passed\n", "3 seconds have passed\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "TimeoutError (expected)\n" ] } ], "source": [ "with ExpectTimeout(5, print_traceback=False):\n", " with ExpectTimeout(3, print_traceback=False):\n", " long_running_test()\n", " long_running_test()" ] }, { "cell_type": "markdown", "metadata": { "button": false, "new_sheet": false, "run_control": { "read_only": false }, "slideshow": { "slide_type": "subslide" } }, "source": [ "That's it, folks – enjoy!" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Synopsis\n", "\n", "The `ExpectError` class allows you to catch and report exceptions, yet resume execution. This is useful in notebooks, as they would normally interrupt execution as soon as an exception is raised. Its typical usage is in conjunction with a `with` clause:" ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "execution": { "iopub.execute_input": "2024-01-18T17:31:07.162041Z", "iopub.status.busy": "2024-01-18T17:31:07.161388Z", "iopub.status.idle": "2024-01-18T17:31:07.166663Z", "shell.execute_reply": "2024-01-18T17:31:07.165650Z" }, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "Traceback (most recent call last):\n", " File \"/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_82852/2664980466.py\", line 2, in \n", " x = 1 / 0\n", "ZeroDivisionError: division by zero (expected)\n" ] } ], "source": [ "with ExpectError():\n", " x = 1 / 0" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "The `ExpectTimeout` class allows you to interrupt execution after the specified time. This is useful for interrupting code that might otherwise run forever." ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "execution": { "iopub.execute_input": "2024-01-18T17:31:07.170943Z", "iopub.status.busy": "2024-01-18T17:31:07.170433Z", "iopub.status.idle": "2024-01-18T17:31:12.183464Z", "shell.execute_reply": "2024-01-18T17:31:12.181450Z" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Start\n", "0 seconds have passed\n", "1 seconds have passed\n", "2 seconds have passed\n", "3 seconds have passed\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "Traceback (most recent call last):\n", " File \"/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_82852/1223755941.py\", line 2, in \n", " long_running_test()\n", " File \"/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_82852/3930412460.py\", line 4, in long_running_test\n", " time.sleep(1)\n", " File \"/Users/zeller/Projects/fuzzingbook/notebooks/Timeout.ipynb\", line 43, in timeout_handler\n", " raise TimeoutError()\n", "TimeoutError (expected)\n" ] } ], "source": [ "with ExpectTimeout(5):\n", " long_running_test()" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "The exception and the associated traceback are printed as error messages. If you do not want that, \n", "use these keyword options:\n", "\n", "* `print_traceback` (default True) can be set to `False` to avoid the traceback being printed\n", "* `mute` (default False) can be set to `True` to completely avoid any output." ] }, { "cell_type": "markdown", "metadata": { "button": false, "new_sheet": true, "run_control": { "read_only": false }, "slideshow": { "slide_type": "slide" } }, "source": [ "## Lessons Learned\n", "\n", "* With the `ExpectError` class, it is very easy to handle errors without interrupting notebook execution." ] } ], "metadata": { "ipub": { "bibliography": "fuzzingbook.bib", "toc": true }, "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.2" }, "toc": { "base_numbering": 1, "nav_menu": {}, "number_sections": true, "sideBar": true, "skip_h1_title": true, "title_cell": "", "title_sidebar": "Contents", "toc_cell": false, "toc_position": {}, "toc_section_display": true, "toc_window_display": true }, "toc-autonumbering": false }, "nbformat": 4, "nbformat_minor": 4 }