{"id":3060,"date":"2021-11-27T05:15:10","date_gmt":"2021-11-27T05:15:10","guid":{"rendered":"https:\/\/www.pythontutorial.net\/?page_id=3060"},"modified":"2025-03-28T03:41:19","modified_gmt":"2025-03-28T03:41:19","slug":"python-exception-handling","status":"publish","type":"page","link":"https:\/\/www.pythontutorial.net\/python-oop\/python-exception-handling\/","title":{"rendered":"Python Exception Handling"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: in this tutorial, you learn how to handle exceptions in Python in the right way by using the <code>try<\/code> statement.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='introduction-to-the-exception-handling-in-python'>Introduction to the exception handling in Python <a href=\"#introduction-to-the-exception-handling-in-python\" class=\"anchor\" id=\"introduction-to-the-exception-handling-in-python\" title=\"Anchor for Introduction to the exception handling in Python\">#<\/a><\/h2>\n\n\n\n<p>To handle exceptions, you use the <code>try<\/code> statement. The <code>try<\/code> statement has the following clauses:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-keyword\">try<\/span>:\n    <span class=\"hljs-comment\"># code that you want to protect from exceptions<\/span>\n<span class=\"hljs-keyword\">except<\/span> &lt;ExceptionType&gt; <span class=\"hljs-keyword\">as<\/span> ex:\n    <span class=\"hljs-comment\"># code that handle the exception<\/span>\n<span class=\"hljs-keyword\">finally<\/span>:\n    <span class=\"hljs-comment\"># code that always execute whether the exception occurred or not<\/span>\n<span class=\"hljs-keyword\">else<\/span>:\n    <span class=\"hljs-comment\"># code that excutes if try execute normally (an except clause must be present)<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Let&#8217;s examine the <code>try<\/code> statement in greater detail.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id='try'>try <a href=\"#try\" class=\"anchor\" id=\"try\" title=\"Anchor for try\">#<\/a><\/h3>\n\n\n\n<p>In the <code>try<\/code> clause, you place the code that protects from one or more potential exceptions. It&#8217;s a good practice to keep the code as short as possible. Often, you&#8217;ll have a single statement in the <code>try<\/code> clause.<\/p>\n\n\n\n<p>The <code>try<\/code> clause appears exactly one time in the <code>try<\/code> statement.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id='except'>except <a href=\"#except\" class=\"anchor\" id=\"except\" title=\"Anchor for except\">#<\/a><\/h3>\n\n\n\n<p>In the <code>except<\/code> clause, you place the code that handles a specific exception type. A <code>try<\/code> statement can have zero or more <code>except<\/code> clauses. Typically, each <code>except<\/code> clause handles different exception types in specific ways. <\/p>\n\n\n\n<p>In an <code>except<\/code> clause, the <code>as ex<\/code> is optional. And the <code>&lt;ExceptionType><\/code> is also optional. However, if you omit the <code>&lt;ExceptionType> as ex<\/code>, you&#8217;ll have a bare exception handler.<\/p>\n\n\n\n<p>When specifying exception types in the <code>except<\/code> clauses, you place the most specific to least specific exceptions from top to bottom.<\/p>\n\n\n\n<p>If you have the same logic that handles different exception types, you can group them in a single <code>except<\/code> clause. For example:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-keyword\">try<\/span>:\n...\n<span class=\"hljs-keyword\">except<\/span> &lt;ExceptionType1&gt; <span class=\"hljs-keyword\">as<\/span> ex:\n    log(ex)\n<span class=\"hljs-keyword\">except<\/span> &lt;ExceptionType2&gt; <span class=\"hljs-keyword\">as<\/span> ex:\n    log(ex)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Become<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-keyword\">try<\/span>:\n...\n<span class=\"hljs-keyword\">except<\/span> (&lt;ExceptionType1&gt;, &lt;ExceptionType2&gt;) <span class=\"hljs-keyword\">as<\/span> ex:\n    log(ex)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>It&#8217;s important to note that the <code>except<\/code> order matters because Python will run the first <code>except<\/code> clause whose exception type matches the occurred exception.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id='finally'>finally <a href=\"#finally\" class=\"anchor\" id=\"finally\" title=\"Anchor for finally\">#<\/a><\/h3>\n\n\n\n<p>The <code>finally<\/code> clause may appear zero or 1 time in a <code>try<\/code> statement. The <code>finally<\/code> clause always executes whether an exception occurred or not.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id='else'>else <a href=\"#else\" class=\"anchor\" id=\"else\" title=\"Anchor for else\">#<\/a><\/h3>\n\n\n\n<p>The <code>else<\/code> clause also appears zero or 1 time. And the <code>else<\/code> clause is only valid if the try statement has at least one <code>except<\/code> clause.<\/p>\n\n\n\n<p>Typically, you place the code that executes if the <code>try<\/code> clause terminates normally.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='python-exception-handling-example'>Python exception handling example <a href=\"#python-exception-handling-example\" class=\"anchor\" id=\"python-exception-handling-example\" title=\"Anchor for Python exception handling example\">#<\/a><\/h2>\n\n\n\n<p>The following defines a function that returns the result of a number by another:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">divide<\/span><span class=\"hljs-params\">(a, b)<\/span>:<\/span>\n    <span class=\"hljs-keyword\">return<\/span> a \/ b<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>If you pass 0 to the second argument, you&#8217;ll get a <code>ZeroDivisionError<\/code> exception:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-5\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">divide(<span class=\"hljs-number\">10<\/span>, <span class=\"hljs-number\">0<\/span>)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-5\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Error:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-6\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">ZeroDivisionError: division by zero<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-6\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>To fix it, you can handle the <code>ZeroDivisionError<\/code> exception in the <code>divide()<\/code> function as follows:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-7\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">divide<\/span><span class=\"hljs-params\">(a, b)<\/span>:<\/span>\n    <span class=\"hljs-keyword\">try<\/span>:\n        <span class=\"hljs-keyword\">return<\/span> a \/ b\n    <span class=\"hljs-keyword\">except<\/span> ZeroDivisionError <span class=\"hljs-keyword\">as<\/span> ex:\n        <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-literal\">None<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-7\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>In this example, the <code>divide()<\/code> function returns <code>None<\/code> if the <code>ZeroDivisionError<\/code> occurs:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-8\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">divide<\/span><span class=\"hljs-params\">(a, b)<\/span>:<\/span>\n    <span class=\"hljs-keyword\">try<\/span>:\n        <span class=\"hljs-keyword\">return<\/span> a \/ b\n    <span class=\"hljs-keyword\">except<\/span> ZeroDivisionError <span class=\"hljs-keyword\">as<\/span> ex:\n        <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-literal\">None<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-8\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>When using the <code>divide()<\/code> function, you need to check if the result is <code>None<\/code>:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-9\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">result = divide(<span class=\"hljs-number\">10<\/span>, <span class=\"hljs-number\">0<\/span>)\n\n<span class=\"hljs-keyword\">if<\/span> result <span class=\"hljs-keyword\">is<\/span> <span class=\"hljs-keyword\">not<\/span> <span class=\"hljs-literal\">None<\/span>:\n    print(<span class=\"hljs-string\">'result:'<\/span>, result)\n<span class=\"hljs-keyword\">else<\/span>:\n    print(<span class=\"hljs-string\">'Invalid inputs'<\/span>)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-9\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>But returning <code>None<\/code> may not be the best because others may accidentally evaluate the result in the <code>if<\/code> statement like this:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-10\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">result = divide(<span class=\"hljs-number\">10<\/span>, <span class=\"hljs-number\">0<\/span>)\n\n<span class=\"hljs-keyword\">if<\/span> result:\n    print(<span class=\"hljs-string\">'result:'<\/span>, result)\n<span class=\"hljs-keyword\">else<\/span>:\n    print(<span class=\"hljs-string\">'Invalid inputs'<\/span>)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-10\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>In this case, it works. However, it won&#8217;t work if the first argument is zero. For example:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-11\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">result = divide(<span class=\"hljs-number\">0<\/span>, <span class=\"hljs-number\">10<\/span>)\n\n<span class=\"hljs-keyword\">if<\/span> result:\n    print(<span class=\"hljs-string\">'result:'<\/span>, result)\n<span class=\"hljs-keyword\">else<\/span>:\n    print(<span class=\"hljs-string\">'Invalid inputs'<\/span>)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-11\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>A better approach is to raise an exception to the caller if the <code>ZeroDivisionError<\/code> exception occurred. For example:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-12\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">divide<\/span><span class=\"hljs-params\">(a, b)<\/span>:<\/span>\n    <span class=\"hljs-keyword\">try<\/span>:\n        <span class=\"hljs-keyword\">return<\/span> a \/ b\n    <span class=\"hljs-keyword\">except<\/span> ZeroDivisionError <span class=\"hljs-keyword\">as<\/span> ex:\n        <span class=\"hljs-keyword\">raise<\/span> ValueError(<span class=\"hljs-string\">'The second argument (b) must not be zero'<\/span>)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-12\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>In this example, the <code>divide()<\/code> function will raise an error if <code>b<\/code> is zero. To use the <code>divide()<\/code> function, you need to catch the <code>ValueError<\/code> exception:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-13\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">divide<\/span><span class=\"hljs-params\">(a, b)<\/span>:<\/span>\n    <span class=\"hljs-keyword\">try<\/span>:\n        <span class=\"hljs-keyword\">return<\/span> a \/ b\n    <span class=\"hljs-keyword\">except<\/span> ZeroDivisionError <span class=\"hljs-keyword\">as<\/span> ex:\n        <span class=\"hljs-keyword\">raise<\/span> ValueError(<span class=\"hljs-string\">'The second argument (b) must not be zero'<\/span>)\n\n\n<span class=\"hljs-keyword\">try<\/span>:\n    result = divide(<span class=\"hljs-number\">10<\/span>, <span class=\"hljs-number\">0<\/span>)\n<span class=\"hljs-keyword\">except<\/span> ValueError <span class=\"hljs-keyword\">as<\/span> e:\n    print(e)\n<span class=\"hljs-keyword\">else<\/span>:\n    print(<span class=\"hljs-string\">'result:'<\/span>, result)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-13\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-14\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">The second argument (b) must <span class=\"hljs-keyword\">not<\/span> be zero<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-14\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>It&#8217;s a good practice to raise an exception instead of returning <code>None<\/code> in special cases.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='except-order-example'>Except order example <a href=\"#except-order-example\" class=\"anchor\" id=\"except-order-example\" title=\"Anchor for Except order example\">#<\/a><\/h2>\n\n\n\n<p>When you catch an exception in the except clause, you need to place the exceptions from most specific to the least specific in terms of exception hierarchy.<\/p>\n\n\n\n<p>The following shows three exception classes: <code>Exception<\/code>, <code>LookupError<\/code>, and <code>IndexError<\/code>:<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-full\"><img decoding=\"async\" src=\"https:\/\/www.pythontutorial.net\/wp-content\/uploads\/2021\/11\/python-exception-handling.svg\" alt=\"\" class=\"wp-image-3069\"\/><\/figure><\/div>\n\n\n\n<p>If you catch the exception, you need to place them in the following order: IndexError, LookupErorr, and Exception.<\/p>\n\n\n\n<p>For example, the following defines a list of three strings and attempts to access the 4th element:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-15\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">colors = &#91;<span class=\"hljs-string\">'red'<\/span>, <span class=\"hljs-string\">'green'<\/span>, <span class=\"hljs-string\">'blue'<\/span>]\n<span class=\"hljs-keyword\">try<\/span>:\n    print(colors&#91;<span class=\"hljs-number\">3<\/span>])\n<span class=\"hljs-keyword\">except<\/span> IndexError <span class=\"hljs-keyword\">as<\/span> e:\n    print(type(e), <span class=\"hljs-string\">'Index error'<\/span>)\n<span class=\"hljs-keyword\">except<\/span> LookupError <span class=\"hljs-keyword\">as<\/span> e:\n    print(type(e), <span class=\"hljs-string\">'Lookup error'<\/span>)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-15\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>It issues the following error:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-16\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">&lt;<span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> '<span class=\"hljs-title\">IndexError<\/span>'&gt; <span class=\"hljs-title\">Index<\/span> <span class=\"hljs-title\">error<\/span><\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-16\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>The <code>colors[3]<\/code> access causes an <code>IndexError<\/code> exception. However, if you swap the <code>except<\/code> clauses and catch the <code>LookupError<\/code> first and the <code>IndexError<\/code> second like this:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-17\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">colors = &#91;<span class=\"hljs-string\">'red'<\/span>, <span class=\"hljs-string\">'green'<\/span>, <span class=\"hljs-string\">'blue'<\/span>]\n<span class=\"hljs-keyword\">try<\/span>:\n    print(colors&#91;<span class=\"hljs-number\">3<\/span>])\n<span class=\"hljs-keyword\">except<\/span> LookupError <span class=\"hljs-keyword\">as<\/span> e:\n    print(type(e), <span class=\"hljs-string\">'Lookup error'<\/span>)\n<span class=\"hljs-keyword\">except<\/span> IndexError <span class=\"hljs-keyword\">as<\/span> e:\n    print(type(e), <span class=\"hljs-string\">'Index error'<\/span>)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-17\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-18\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">&lt;<span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> '<span class=\"hljs-title\">IndexError<\/span>'&gt; <span class=\"hljs-title\">Lookup<\/span> <span class=\"hljs-title\">error<\/span><\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-18\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>The exception is still <code>IndexError<\/code> but the following message is misleading. <\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='bare-exception-handlers'>Bare exception handlers <a href=\"#bare-exception-handlers\" class=\"anchor\" id=\"bare-exception-handlers\" title=\"Anchor for Bare exception handlers\">#<\/a><\/h2>\n\n\n\n<p>When you want to catch any exception, you can use the bare exception handlers. A bare exception handler does not specify an exception type:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-19\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-keyword\">try<\/span>:\n    ...\n<span class=\"hljs-keyword\">except<\/span>:\n    ...<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-19\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>It&#8217;s equivalent to the following:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-20\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-keyword\">try<\/span>:\n    ...\n<span class=\"hljs-keyword\">except<\/span> BaseException:\n\n    ...<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-20\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>A bare exception handler will catch any exceptions including the SystemExit and KeyboardInterupt exceptions. <\/p>\n\n\n\n<p>A bare exception will make it harder to interrupt a program with Control-C and disguise other programs.<\/p>\n\n\n\n<p>If you want to catch all exceptions that signal program errors, you can use except Exception instead:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-21\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-keyword\">try<\/span>:\n    ...\n<span class=\"hljs-keyword\">except<\/span> Exception:\n    ...<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-21\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>In practice, you should avoid using bare exception handlers. If you don&#8217;t know exceptions to catch, just let the exception occurs and then modify the code to handle these exceptions.<\/p>\n\n\n\n<p>To get exception information from a bare exception handler, you use the <code>exc_info()<\/code> function from the <code>sys<\/code> module.<\/p>\n\n\n\n<p>The <code>sys.exc_info()<\/code> function returns a tuple that consists of three values:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><code>type<\/code> is the type of the exception occurred. It&#8217;s a subclass of the <code>BaseException<\/code>.<\/li><li><code>value<\/code> is the instance of the exception type.<\/li><li><code>traceback<\/code> is an object that encapsulates the call stack at the point where the exception originally ocurred.<\/li><\/ul>\n\n\n\n<p>The following example uses the <code>sys.exc_info()<\/code> function to examine the exception when  a string is divided by a number:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-22\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-keyword\">import<\/span> sys\n\n<span class=\"hljs-keyword\">try<\/span>:\n    <span class=\"hljs-string\">'20'<\/span> \/ <span class=\"hljs-number\">2<\/span>\n<span class=\"hljs-keyword\">except<\/span>:\n    exc_info = sys.exc_info()\n    print(exc_info)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-22\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-23\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">(&lt;<span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> '<span class=\"hljs-title\">TypeError<\/span>'&gt;, <span class=\"hljs-title\">TypeError<\/span><span class=\"hljs-params\">(<span class=\"hljs-string\">\"unsupported operand type(s) for \/: 'str' and 'int'\"<\/span>)<\/span>, &lt;<span class=\"hljs-title\">traceback<\/span> <span class=\"hljs-title\">object<\/span> <span class=\"hljs-title\">at<\/span> 0<span class=\"hljs-title\">x000001F19F42E700<\/span>&gt;)<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-23\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>The output shows that the code in the try clause causes a <code>TypeError<\/code> exception. Therefore, you can modify the code to handle it specifically as follows:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-24\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-keyword\">try<\/span>:\n    <span class=\"hljs-string\">'20'<\/span> \/ <span class=\"hljs-number\">2<\/span>\n<span class=\"hljs-keyword\">except<\/span> TypeError <span class=\"hljs-keyword\">as<\/span> e:\n    print(e)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-24\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-25\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">unsupported operand type(s) <span class=\"hljs-keyword\">for<\/span> \/: <span class=\"hljs-string\">'str'<\/span> <span class=\"hljs-keyword\">and<\/span> <span class=\"hljs-string\">'int'<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-25\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\" id='summary'>Summary <a href=\"#summary\" class=\"anchor\" id=\"summary\" title=\"Anchor for Summary\">#<\/a><\/h2>\n\n\n\n<ul class=\"wp-block-list\"><li>Use the <code>try<\/code> statement to handle exception.<\/li><li>Place only minimal code that you want to protect from potential exceptions in the <code>try<\/code> clause.<\/li><li>Handle exceptions from most specific to least specific in terms of exception types. The order of <code>except<\/code> clauses is important.<\/li><li>The finally always executes whether the exceptions occurred or not.<\/li><li>The <code>else<\/code> clause only executes when the <code>try<\/code> clause terminates normally. The <code>else<\/code> clause is valid only if the <code>try<\/code> statement has at least one <code>except<\/code> clause.<\/li><li>Avoid using bare exception handlers.<\/li><\/ul>\n<div class=\"helpful-block-content\" data-title=\"\">\n\t<header>\n\t\t<div class=\"wth-question\">Was this tutorial helpful ?<\/div>\n\t\t<div class=\"wth-thumbs\">\n\t\t\t<button\n\t\t\t\tdata-post=\"3060\"\n\t\t\t\tdata-post-url=\"https:\/\/www.pythontutorial.net\/python-oop\/python-exception-handling\/\"\n\t\t\t\tdata-post-title=\"Python Exception Handling\"\n\t\t\t\tdata-response=\"1\"\n\t\t\t\tclass=\"wth-btn-rounded wth-yes-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t\tclass=\"feather feather-thumbs-up block w-full h-full\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.28a2 2 0 0 0 2-1.7l1.38-9a2 2 0 0 0-2-2.3zM7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> Yes <\/span>\n\t\t\t<\/button>\n\n\t\t\t<button\n\t\t\t\tdata-response=\"0\"\n\t\t\t\tdata-post=\"3060\"\n\t\t\t\tdata-post-url=\"https:\/\/www.pythontutorial.net\/python-oop\/python-exception-handling\/\"\n\t\t\t\tdata-post-title=\"Python Exception Handling\"\n\t\t\t\tclass=\"wth-btn-rounded wth-no-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M10 15v4a3 3 0 0 0 3 3l4-9V2H5.72a2 2 0 0 0-2 1.7l-1.38 9a2 2 0 0 0 2 2.3zm7-13h2.67A2.31 2.31 0 0 1 22 4v7a2.31 2.31 0 0 1-2.33 2H17\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> No <\/span>\n\t\t\t<\/button>\n\t\t<\/div>\n\t<\/header>\n\n\t<div class=\"wth-form hidden\">\n\t\t<div class=\"wth-form-wrapper\">\n\t\t\t<div class=\"wth-title\"><\/div>\n\t\t\t<textarea class=\"wth-message\"><\/textarea>\n\t\t\t<input type=\"button\" name=\"wth-submit\" class=\"wth-btn wth-btn-submit\" id=\"wth-submit\" \/>\n\t\t\t<input type=\"button\" class=\"wth-btn wth-btn-cancel\" value=\"Cancel\" \/>\n\t\t<\/div>\n\t<\/div>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>In this tutorial, you learn how to handle exceptions in Python in the right way.<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":417,"menu_order":46,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-3060","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/3060","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/comments?post=3060"}],"version-history":[{"count":1,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/3060\/revisions"}],"predecessor-version":[{"id":7185,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/3060\/revisions\/7185"}],"up":[{"embeddable":true,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/417"}],"wp:attachment":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/media?parent=3060"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}