{"id":871,"date":"2020-10-29T01:19:55","date_gmt":"2020-10-29T01:19:55","guid":{"rendered":"https:\/\/www.pythontutorial.net\/?page_id=871"},"modified":"2025-03-30T10:21:58","modified_gmt":"2025-03-30T10:21:58","slug":"python-try-except","status":"publish","type":"page","link":"https:\/\/www.pythontutorial.net\/python-basics\/python-try-except\/","title":{"rendered":"Python try&#8230;except"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: in this tutorial, you&#8217;ll learn how to use the Python <code>try...except<\/code> statement to handle exceptions gracefully.<\/p>\n\n\n\n<p>In Python, there&#8217;re two main kinds of errors: syntax errors and exceptions.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='syntax-errors'>Syntax errors <a href=\"#syntax-errors\" class=\"anchor\" id=\"syntax-errors\" title=\"Anchor for Syntax errors\">#<\/a><\/h2>\n\n\n\n<p>When you write an invalid Python code, you&#8217;ll get a syntax error. For example:<\/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\">current = <span class=\"hljs-number\">1<\/span>\n<span class=\"hljs-keyword\">if<\/span> current &lt; <span class=\"hljs-number\">10<\/span>\ncurrent += <span class=\"hljs-number\">1<\/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>If you attempt to run this code, you&#8217;ll get the following error:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"Shell Session\" data-shcb-language-slug=\"shell\"><span><code class=\"hljs language-shell\">File \"d:\/python\/try-except.py\", line 2\n    if current &lt; 10\n                  ^\nSyntaxError: invalid syntax<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Shell Session<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">shell<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>In this example, the Python interpreter detected the error at the <a href=\"https:\/\/www.pythontutorial.net\/python-basics\/python-if\/\"><code>if<\/code> statement<\/a> since a colon (<code>:<\/code>) is missing after it.<\/p>\n\n\n\n<p>The Python interpreter shows the file name and line number where the error occurred so that you can fix it.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='exceptions'>Exceptions <a href=\"#exceptions\" class=\"anchor\" id=\"exceptions\" title=\"Anchor for Exceptions\">#<\/a><\/h2>\n\n\n\n<p>Even though when your code has valid syntax, it may cause an error during execution.<\/p>\n\n\n\n<p>In Python, errors that occur during the execution are called <strong>exceptions<\/strong>. The causes of exceptions mainly come from the environment where the code executes. For example:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/www.pythontutorial.net\/python-basics\/python-read-text-file\/\">Reading a file<\/a> that doesn&#8217;t <a href=\"https:\/\/www.pythontutorial.net\/python-basics\/python-check-if-file-exists\/\">exist<\/a>.<\/li>\n\n\n\n<li>Connecting to a remote server that is offline.<\/li>\n\n\n\n<li>Bad user inputs.<\/li>\n<\/ul>\n\n\n\n<p>When an exception occurs, the program doesn&#8217;t handle it automatically. This results in an error message.<\/p>\n\n\n\n<p>For example, the following program calculates the sales growth:<\/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-comment\"># get input net sales<\/span>\nprint(<span class=\"hljs-string\">'Enter the net sales for'<\/span>)\n\nprevious = float(input(<span class=\"hljs-string\">'- Prior period:'<\/span>))\ncurrent = float(input(<span class=\"hljs-string\">'- Current period:'<\/span>))\n\n<span class=\"hljs-comment\"># calculate the change in percentage<\/span>\nchange = (current - previous) * <span class=\"hljs-number\">100<\/span> \/ previous\n\n<span class=\"hljs-comment\"># show the result<\/span>\n<span class=\"hljs-keyword\">if<\/span> change &gt; <span class=\"hljs-number\">0<\/span>:\n    result = <span class=\"hljs-string\">f'Sales increase <span class=\"hljs-subst\">{abs(change)}<\/span>%'<\/span>\n<span class=\"hljs-keyword\">else<\/span>:\n    result = <span class=\"hljs-string\">f'Sales decrease <span class=\"hljs-subst\">{abs(change)}<\/span>%'<\/span>\n\nprint(result)<\/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>How it works.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>First, prompt users for entering two numbers: the net sales of the prior and current periods.<\/li>\n\n\n\n<li>Then, calculate the sales growth in percentage and show the result.<\/li>\n<\/ul>\n\n\n\n<p>When you run the program and enter <code>120'<\/code> as the net sales of the current period, the Python interpreter will issue the following output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"Shell Session\" data-shcb-language-slug=\"shell\"><span><code class=\"hljs language-shell\">Enter the net sales for\n- Prior period:100\n- Current period:120'\nTraceback (most recent call last):\n  File \"d:\/python\/try-except.py\", line 5, in &lt;module&gt;\n    current = float(input('- Current period:'))\nValueError: could not convert string to float: \"120'\"<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Shell Session<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">shell<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>The Python interpreter showed a traceback that includes detailed information of the exception:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The path to the source code file (<code>d:\/python\/try-except.py<\/code>) that caused the exception.<\/li>\n\n\n\n<li>The exact line of code that caused the exception (<code>line 5<\/code>)<\/li>\n\n\n\n<li>The statement that caused the exception <code>current = float(input('- Current period:'))<\/code><\/li>\n\n\n\n<li>The type of exception <code>ValueError<\/code><\/li>\n\n\n\n<li>The error message: <code>ValueError: could not convert string to float: \"120'\"<\/code><\/li>\n<\/ul>\n\n\n\n<p>Because <code>float()<\/code> couldn&#8217;t convert the string <code>120'<\/code> to a number, the Python interpreter issued a <code>ValueError<\/code> exception.<\/p>\n\n\n\n<p>In Python, exceptions have different types such as <code>TypeError<\/code>, <code>NameError<\/code>, etc.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='handling-exceptions'>Handling exceptions <a href=\"#handling-exceptions\" class=\"anchor\" id=\"handling-exceptions\" title=\"Anchor for Handling exceptions\">#<\/a><\/h2>\n\n\n\n<p>To make the program more robust, you need to handle the exception once it occurs. In other words, you need to catch the exception and inform users so that they can fix it.<\/p>\n\n\n\n<p>A good way to handle this is not to show what the Python interpreter returns. Instead, you replace that error message with a more user-friendly one.<\/p>\n\n\n\n<p>To do that, you can use the Python <code>try...except<\/code> statement:<\/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\"><span class=\"hljs-keyword\">try<\/span>:\n    <span class=\"hljs-comment\"># code that may cause error<\/span>\n<span class=\"hljs-keyword\">except<\/span>:\n    <span class=\"hljs-comment\"># handle errors<\/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>The <code>try...except<\/code> statement works as follows:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The statements in the <code>try<\/code> clause execute first.<\/li>\n\n\n\n<li>If no exception occurs, the <code>except<\/code> clause is skipped and the execution of the <code>try<\/code> statement is completed.<\/li>\n\n\n\n<li>If an exception occurs at any statement in the <code>try<\/code> clause, the <strong>rest of the clause is skipped<\/strong> and the <code>except<\/code> clause is executed.<\/li>\n<\/ul>\n\n\n\n<p>The following flowchart illustrates the <code>try...except<\/code> statement:<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"320\" height=\"472\" src=\"https:\/\/www.pythontutorial.net\/wp-content\/uploads\/2020\/10\/Python-try-except.png\" alt=\"Python try...except\" class=\"wp-image-877\" srcset=\"https:\/\/www.pythontutorial.net\/wp-content\/uploads\/2020\/10\/Python-try-except.png 320w, https:\/\/www.pythontutorial.net\/wp-content\/uploads\/2020\/10\/Python-try-except-203x300.png 203w\" sizes=\"auto, (max-width: 320px) 100vw, 320px\" \/><\/figure>\n<\/div>\n\n\n<p>So to handle exceptions using the <code>try...except<\/code> statement, you place the code that may cause an exception in the <code>try<\/code> clause and the code that handles exceptions in the <code>except<\/code> clause.<\/p>\n\n\n\n<p>Here&#8217;s how you can rewrite the program and uses the <code>try...except<\/code> statement to handle the exception:<\/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\"><span class=\"hljs-keyword\">try<\/span>:\n    <span class=\"hljs-comment\"># get input net sales<\/span>\n    print(<span class=\"hljs-string\">'Enter the net sales for'<\/span>)\n\n    previous = float(input(<span class=\"hljs-string\">'- Prior period:'<\/span>))\n    current = float(input(<span class=\"hljs-string\">'- Current period:'<\/span>))\n\n    <span class=\"hljs-comment\"># calculate the change in percentage<\/span>\n    change = (current - previous) * <span class=\"hljs-number\">100<\/span> \/ previous\n\n    <span class=\"hljs-comment\"># show the result<\/span>\n    <span class=\"hljs-keyword\">if<\/span> change &gt; <span class=\"hljs-number\">0<\/span>:\n        result = <span class=\"hljs-string\">f'Sales increase <span class=\"hljs-subst\">{abs(change)}<\/span>%'<\/span>\n    <span class=\"hljs-keyword\">else<\/span>:\n        result = <span class=\"hljs-string\">f'Sales decrease <span class=\"hljs-subst\">{abs(change)}<\/span>%'<\/span>\n\n    print(result)\n<span class=\"hljs-keyword\">except<\/span>:\n    print(<span class=\"hljs-string\">'Error! Please enter a number for net sales.'<\/span>)\n<\/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>If you run the program again and enter the net sales which is not a number, the program will issue the message that you specified in the <code>except<\/code> block instead:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-7\" data-shcb-language-name=\"Shell Session\" data-shcb-language-slug=\"shell\"><span><code class=\"hljs language-shell\">Enter the net sales for\n- Prior period:100\n- Current period:120'\nError! Please enter a number for net sales.<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-7\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Shell Session<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">shell<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\" id='catching-specific-exceptions'>Catching specific exceptions <a href=\"#catching-specific-exceptions\" class=\"anchor\" id=\"catching-specific-exceptions\" title=\"Anchor for Catching specific exceptions\">#<\/a><\/h2>\n\n\n\n<p>When you enter the net sales of the prior period as zero, you&#8217;ll get the following message:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-8\" data-shcb-language-name=\"Shell Session\" data-shcb-language-slug=\"shell\"><span><code class=\"hljs language-shell\">Enter the net sales for\n- Prior period:0\n- Current period:100\nError! Please enter a number for net sales.<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-8\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Shell Session<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">shell<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>In this case, both net sales of the prior and current periods are numbers, but the program still issues an error message. Another exception must occur.<\/p>\n\n\n\n<p>The <code>try...except<\/code> statement allows you to handle a particular exception. To catch a selected exception, you place the type of exception after the <code>except<\/code> keyword:<\/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\"><span class=\"hljs-keyword\">try<\/span>:\n    <span class=\"hljs-comment\"># code that may cause an exception<\/span>\n<span class=\"hljs-keyword\">except<\/span> ValueError <span class=\"hljs-keyword\">as<\/span> error:\n    <span class=\"hljs-comment\"># code to handle the exception<\/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>For example:<\/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\"><span class=\"hljs-keyword\">try<\/span>:\n    <span class=\"hljs-comment\"># get input net sales<\/span>\n    print(<span class=\"hljs-string\">'Enter the net sales for'<\/span>)\n\n    previous = float(input(<span class=\"hljs-string\">'- Prior period:'<\/span>))\n    current = float(input(<span class=\"hljs-string\">'- Current period:'<\/span>))\n\n    <span class=\"hljs-comment\"># calculate the change in percentage<\/span>\n    change = (current - previous) * <span class=\"hljs-number\">100<\/span> \/ previous\n\n    <span class=\"hljs-comment\"># show the result<\/span>\n    <span class=\"hljs-keyword\">if<\/span> change &gt; <span class=\"hljs-number\">0<\/span>:\n        result = <span class=\"hljs-string\">f'Sales increase <span class=\"hljs-subst\">{abs(change)}<\/span>%'<\/span>\n    <span class=\"hljs-keyword\">else<\/span>:\n        result = <span class=\"hljs-string\">f'Sales decrease <span class=\"hljs-subst\">{abs(change)}<\/span>%'<\/span>\n\n    print(result)\n<span class=\"hljs-keyword\">except<\/span> ValueError:\n    print(<span class=\"hljs-string\">'Error! Please enter a number for net sales.'<\/span>)\n<\/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>When you run a program and enter a string for the net sales, you&#8217;ll get the same error message.<\/p>\n\n\n\n<p>However, if you enter zero for the net sales of the prior period:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-11\" data-shcb-language-name=\"Shell Session\" data-shcb-language-slug=\"shell\"><span><code class=\"hljs language-shell\">Enter the net sales for\n- Prior period:0\n- Current period:100<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-11\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Shell Session<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">shell<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>&#8230; you&#8217;ll get the following error message:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-12\" data-shcb-language-name=\"Shell Session\" data-shcb-language-slug=\"shell\"><span><code class=\"hljs language-shell\">Traceback (most recent call last):\n  File \"d:\/python\/try-except.py\", line 9, in &lt;module&gt;\n    change = (current - previous) * 100 \/ previous\nZeroDivisionError: float division by zero<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-12\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Shell Session<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">shell<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>This time you got the  <code>ZeroDivisionError<\/code> exception. This division by zero exception is caused by the following statement:<\/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\">change = (current - previous) * <span class=\"hljs-number\">100<\/span> \/ previous<\/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>And the reason is that the value of the <code>previous<\/code> is zero.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='handling-multiple-exceptions'>Handling multiple exceptions <a href=\"#handling-multiple-exceptions\" class=\"anchor\" id=\"handling-multiple-exceptions\" title=\"Anchor for Handling multiple exceptions\">#<\/a><\/h2>\n\n\n\n<p>The <code>try...except<\/code> allows you to handle multiple exceptions by specifying multiple <code>except<\/code> clauses:<\/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\"><span class=\"hljs-keyword\">try<\/span>:\n    <span class=\"hljs-comment\"># code that may cause an exception<\/span>\n<span class=\"hljs-keyword\">except<\/span> Exception1 <span class=\"hljs-keyword\">as<\/span> e1:\n    <span class=\"hljs-comment\"># handle exception<\/span>\n<span class=\"hljs-keyword\">except<\/span> Exception2 <span class=\"hljs-keyword\">as<\/span> e2:\n    <span class=\"hljs-comment\"># handle exception<\/span>\n<span class=\"hljs-keyword\">except<\/span> Exception3 <span class=\"hljs-keyword\">as<\/span> e3:\n    <span class=\"hljs-comment\"># handle exception <\/span><\/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>This allows you to respond to each type of exception differently.<\/p>\n\n\n\n<p>If you want to have the same response to some types of exceptions, you can group them into one <code>except<\/code> clause:<\/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\"><span class=\"hljs-keyword\">try<\/span>:\n    <span class=\"hljs-comment\"># code that may cause an exception<\/span>\n<span class=\"hljs-keyword\">except<\/span> (Exception1, Exception2):\n    <span class=\"hljs-comment\"># handle exception<\/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>The following example shows how to use the <code>try...except<\/code> to handle the <code>ValueError<\/code> and <code>ZeroDivisionError<\/code> exceptions:<\/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\"><span class=\"hljs-keyword\">try<\/span>:\n    <span class=\"hljs-comment\"># get input net sales<\/span>\n    print(<span class=\"hljs-string\">'Enter the net sales for'<\/span>)\n\n    previous = float(input(<span class=\"hljs-string\">'- Prior period:'<\/span>))\n    current = float(input(<span class=\"hljs-string\">'- Current period:'<\/span>))\n\n    <span class=\"hljs-comment\"># calculate the change in percentage<\/span>\n    change = (current - previous) * <span class=\"hljs-number\">100<\/span> \/ previous\n\n    <span class=\"hljs-comment\"># show the result<\/span>\n    <span class=\"hljs-keyword\">if<\/span> change &gt; <span class=\"hljs-number\">0<\/span>:\n        result = <span class=\"hljs-string\">f'Sales increase <span class=\"hljs-subst\">{abs(change)}<\/span>%'<\/span>\n    <span class=\"hljs-keyword\">else<\/span>:\n        result = <span class=\"hljs-string\">f'Sales decrease <span class=\"hljs-subst\">{abs(change)}<\/span>%'<\/span>\n\n    print(result)\n<span class=\"hljs-keyword\">except<\/span> ValueError:\n    print(<span class=\"hljs-string\">'Error! Please enter a number for net sales.'<\/span>)\n<span class=\"hljs-keyword\">except<\/span> ZeroDivisionError:\n    print(<span class=\"hljs-string\">'Error! The prior net sales cannot be zero.'<\/span>)\n<\/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>When you enter zero for the net sales of the prior period:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-17\" data-shcb-language-name=\"Shell Session\" data-shcb-language-slug=\"shell\"><span><code class=\"hljs language-shell\">Enter the net sales for\n- Prior period:0\n- Current period:120<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-17\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Shell Session<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">shell<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>&#8230; you&#8217;ll get the following error:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-18\" data-shcb-language-name=\"Shell Session\" data-shcb-language-slug=\"shell\"><span><code class=\"hljs language-shell\">Error! The prior net sales cannot be zero.<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-18\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Shell Session<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">shell<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>It&#8217;s a good practice to catch other general errors by placing the <code>catch Exception<\/code> block at the end of the list:<\/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    <span class=\"hljs-comment\"># get input net sales<\/span>\n    print(<span class=\"hljs-string\">'Enter the net sales for'<\/span>)\n\n    previous = float(input(<span class=\"hljs-string\">'- Prior period:'<\/span>))\n    current = float(input(<span class=\"hljs-string\">'- Current period:'<\/span>))\n\n    <span class=\"hljs-comment\"># calculate the change in percentage<\/span>\n    change = (current - previous) * <span class=\"hljs-number\">100<\/span> \/ previous\n\n    <span class=\"hljs-comment\"># show the result<\/span>\n    <span class=\"hljs-keyword\">if<\/span> change &gt; <span class=\"hljs-number\">0<\/span>:\n        result = <span class=\"hljs-string\">f'Sales increase <span class=\"hljs-subst\">{abs(change)}<\/span>%'<\/span>\n    <span class=\"hljs-keyword\">else<\/span>:\n        result = <span class=\"hljs-string\">f'Sales decrease <span class=\"hljs-subst\">{abs(change)}<\/span>%'<\/span>\n\n    print(result)\n<span class=\"hljs-keyword\">except<\/span> ValueError:\n    print(<span class=\"hljs-string\">'Error! Please enter a number for net sales.'<\/span>)\n<span class=\"hljs-keyword\">except<\/span> ZeroDivisionError:\n    print(<span class=\"hljs-string\">'Error! The prior net sales cannot be zero.'<\/span>)\n<span class=\"hljs-keyword\">except<\/span> Exception <span class=\"hljs-keyword\">as<\/span> error:\n    print(error)<\/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<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\">\n<li>Use Python <code>try...except<\/code> statement to handle exceptions gracefully.<\/li>\n\n\n\n<li>Use specific exceptions in the <code>except<\/code> block as much as possible.<\/li>\n\n\n\n<li>Use the <code>except Exception<\/code> statement to catch other exceptions.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id='quiz'>Quiz <a href=\"#quiz\" class=\"anchor\" id=\"quiz\" title=\"Anchor for Quiz\">#<\/a><\/h2>\n\n\n\n<iframe loading=\"lazy\"\n  name=\"quiz\"\n  src=\"\/quiz\/?quiz=try-except\"\n  height=\"700\"\n  width=\"600\"\n  class=\"iframe\"\n><\/iframe>\n\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=\"871\"\n\t\t\t\tdata-post-url=\"https:\/\/www.pythontutorial.net\/python-basics\/python-try-except\/\"\n\t\t\t\tdata-post-title=\"Python try&#8230;except\"\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=\"871\"\n\t\t\t\tdata-post-url=\"https:\/\/www.pythontutorial.net\/python-basics\/python-try-except\/\"\n\t\t\t\tdata-post-title=\"Python try&#8230;except\"\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&#8217;ll learn how to use the Python try&#8230;except statement to handle exceptions gracefully.<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":37,"menu_order":62,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-871","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/871","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=871"}],"version-history":[{"count":1,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/871\/revisions"}],"predecessor-version":[{"id":7220,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/871\/revisions\/7220"}],"up":[{"embeddable":true,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/37"}],"wp:attachment":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/media?parent=871"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}