{"id":222,"date":"2023-12-28T10:59:02","date_gmt":"2023-12-28T16:59:02","guid":{"rendered":"https:\/\/www.baizhao666.com\/?p=222"},"modified":"2024-07-17T18:44:47","modified_gmt":"2024-07-18T00:44:47","slug":"python-try-except","status":"publish","type":"post","link":"https:\/\/www.baizhao666.com\/?p=222","title":{"rendered":"Python Try Except"},"content":{"rendered":"\n<p>When we are making a program, it&#8217;s possible to be interrupted bu some mistakes. These mistakes are sometimes called errors in Python. These errors in python can be Syntax errors and Exceptions. A error in the program will cause the program stop execution. On the other hand, exceptions are raised when some internal events occur which changes the normal flow of the program.<\/p>\n\n\n\n<!--more-->\n\n\n\n<h3 class=\"wp-block-heading\">Try-except<\/h3>\n\n\n\n<p>When Exception errors occur, Try and Except statements are used to handle these errors in python codes. The codes in the try block will be tested when executed. If there is no errors, only the codes in the try block will be executed as normal. When some errors exist, the codes in the except block will be executed. The syntax is:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">try:\n    # some codes may or may not have error\nexcept:\n    # executed if some errors in the try block<\/pre>\n\n\n\n<p>Example 1: use try except but no error exists. Only the try block will be executed.<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-python\" data-lang=\"Python\"><code># try-except without error\ndef division(x, y):\n    try:\n        res = x \/ y\n        print(f&quot;the result of {x}\/{y} is {res}&quot;)\n    except:\n        print(&quot;there are some errors, please check your codes&quot;)\n\ndivision(120, 20)<\/code><\/pre><\/div>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">the result of 120\/20 is 6.0<\/pre>\n\n\n\n<p>Example 2: use try except when some errors exist. Only the except block will be executed.<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-python\" data-lang=\"Python\"><code># try-except with some errors\ndef division(x, y):\n    try:\n        res = x \/ y\n        print(f&quot;the result of {x}\/{y} is {res}&quot;)\n    except:\n        print(&quot;there are some errors, please check your codes&quot;)\n\ndivision(120, 0)<\/code><\/pre><\/div>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">there are some errors, please check your codes<\/pre>\n\n\n\n<p>We can also specify what Exception error we are catching in the except statement.<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-python\" data-lang=\"Python\"><code># specify error type\ndef division(x, y):\n    try:\n        res = x \/ y\n        print(f&quot;the result of {x}\/{y} is {res}&quot;)\n    except ZeroDivisionError:\n        print(&quot;you are dividing by 0&quot;)\n\ndivision(120, 0)<\/code><\/pre><\/div>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">you are dividing by 0<\/pre>\n\n\n\n<p>We can define as many except blocks as we want. The eariest except block that catches the error will be executed. Note: if there is a default except block, it needs to be in the last one.<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-python\" data-lang=\"Python\"><code>def division(x, y):\n    try:\n        res = x \/ y\n        print(f&quot;the result of {x}\/{y} is {res}&quot;)\n    except NameError:\n        print(&quot;there is a name error&quot;)\n    except ZeroDivisionError:\n        print(&quot;you are dividing by 0&quot;)\n    except:\n        print(&quot;some errors exists&quot;)\n\ndivision(120, 0)<\/code><\/pre><\/div>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">you are dividing by 0<\/pre>\n\n\n\n<p>Sometimes we don&#8217;t know exactly what errors may occur, and we would like to know the error type, there is another way of except statement that can show us the error details.<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-python\" data-lang=\"Python\"><code>def division(x, y):\n    try:\n        res = x \/ y\n        print(f&quot;the result of {x}\/{y} is {res}&quot;)\n    except Exception as e:\n        print(f&quot;the error is: {e}&quot;)\n\ndivision(120, 0)\ndivision(3, &quot;a&quot;)<\/code><\/pre><\/div>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">the error is: division by zero\nthe error is: unsupported operand type(s) for \/: 'int' and 'str'<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Try-except-else<\/h3>\n\n\n\n<p>In Python, we can add a else statement <strong>after <\/strong>all except statements. The codes in the else block will be executed <strong>only<\/strong> there is no exception raised in the try block.<\/p>\n\n\n\n<p>The syntax is:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">try:\n    # some codes may or may not have error\nexcept:\n    # executed if some errors in the try block\nelse:\n    # executed if no exception is raised in try block<\/pre>\n\n\n\n<p>For example:<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-python\" data-lang=\"Python\"><code># try-except-else without error\ndef division(x, y):\n    try:\n        res = x \/ y\n    except Exception as e:\n        print(f&quot;the error is: {e}&quot;)\n    else:\n        print(f&quot;the result of {x}\/{y} is {res}&quot;)\n\ndivision(120, 60)\ndivision(3, &quot;a&quot;)<\/code><\/pre><\/div>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">the result of 120\/60 is 2.0\nthe error is: unsupported operand type(s) for \/: 'int' and 'str'<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Try-except-finally<\/h3>\n\n\n\n<p>Python provides a keyword finally, which is always executed after the try and except blocks. The finally block has to be after all try-except blocks, and the codes in the finally block will be executed no matter whether there is error or not.<\/p>\n\n\n\n<p>The syntax is:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">try:\n    # some codes may or may not have error\nexcept:\n    # executed if some errors in the try block\nfinally:\n    # some codes (always executed)<\/pre>\n\n\n\n<p>Small note: the finally block can be used together with else block, but the finally block has to be in the last one.<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-python\" data-lang=\"Python\"><code>def division(x, y):\n    try:\n        res = x \/ y\n    except Exception as e:\n        print(f&quot;the error is: {e}&quot;)\n    else:\n        print(f&quot;the result of {x}\/{y} is {res}&quot;)\n    finally:\n        print(&quot;this function is finished&quot;)\n\nprint(&quot;function call 1:&quot;)\ndivision(120, 60)\nprint(&quot;function call 2:&quot;)\ndivision(3, 0)<\/code><\/pre><\/div>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">function call 1:\nthe result of 120\/60 is 2.0\nthis function is finished\nfunction call 2:\nthe error is: division by zero\nthis function is finished<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Raising a error<\/h3>\n\n\n\n<p>When we are getting inout from user or passing some arguments to a function, it&#8217;s always a good idea to check whether the input is valid to avoid some potential mistake. In this case, instead of using try-except block, we can check the inputs manually and raise an error if the input is invalid.<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-python\" data-lang=\"Python\"><code>def get_input():\n    in_str = input(&quot;please enter a number: &quot;)\n    if not in_str.isdigit():\n        raise ValueError\n    else:\n        print(f&quot;The number you enter is {in_str}&quot;)\n\nget_input()<\/code><\/pre><\/div>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">please enter a number: asc\nTraceback (most recent call last):\n  File \"D:\\PythonProjects\\main.py\", line 83, in &lt;module&gt;\n    get_input()\n  File \"D:\\PythonProjects\\main.py\", line 76, in get_input\n    raise ValueError\nValueError<\/pre>\n\n\n\n<p>More specifically, we can define our own error message in the raise statement to indicate the users.<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-python\" data-lang=\"Python\"><code>def get_input():\n    in_str = input(&quot;please enter a number: &quot;)\n    if not in_str.isdigit():\n        raise ValueError(&quot;You should type a number&quot;)\n    else:\n        print(f&quot;The number you enter is {in_str}&quot;)\n\nget_input()<\/code><\/pre><\/div>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">please enter a number: abc\nTraceback (most recent call last):\n  File \"D:\\PythonProjects\\main.py\", line 83, in &lt;module&gt;\n    get_input()\n  File \"D:\\PythonProjects\\main.py\", line 76, in get_input\n    raise ValueError(\"You should type a number\")\nValueError: You should type a number<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>When we are making a program, it&#8217;s possible to be interrupted bu some mistakes. These mistakes are sometimes called errors in Python. These errors in python can be Syntax errors and Exceptions. A error in the program will cause the program stop execution. On the other hand, exceptions are raised when some internal events occur &hellip; <\/p>\n<p class=\"link-more\"><a href=\"https:\/\/www.baizhao666.com\/?p=222\" class=\"more-link\">Continue reading<span class=\"screen-reader-text\"> &#8220;Python Try Except&#8221;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[4],"tags":[],"class_list":["post-222","post","type-post","status-publish","format-standard","hentry","category-python"],"_links":{"self":[{"href":"https:\/\/www.baizhao666.com\/index.php?rest_route=\/wp\/v2\/posts\/222","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.baizhao666.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.baizhao666.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.baizhao666.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.baizhao666.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=222"}],"version-history":[{"count":4,"href":"https:\/\/www.baizhao666.com\/index.php?rest_route=\/wp\/v2\/posts\/222\/revisions"}],"predecessor-version":[{"id":272,"href":"https:\/\/www.baizhao666.com\/index.php?rest_route=\/wp\/v2\/posts\/222\/revisions\/272"}],"wp:attachment":[{"href":"https:\/\/www.baizhao666.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=222"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.baizhao666.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=222"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.baizhao666.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=222"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}