{"id":329494,"date":"2023-09-20T14:00:00","date_gmt":"2023-09-20T14:00:00","guid":{"rendered":"https:\/\/realpython.com\/python-catch-multiple-exceptions\/"},"modified":"2023-09-20T14:00:00","modified_gmt":"2023-09-20T14:00:00","slug":"how-to-catch-multiple-exceptions-in-python","status":"publish","type":"post","link":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/2023\/09\/20\/how-to-catch-multiple-exceptions-in-python\/","title":{"rendered":"How to Catch Multiple Exceptions in Python"},"content":{"rendered":"<p class=\"syndicated-attribution\"><meta name= \\\"keywords \\\" content= \\\"\u96fb\u5b50\u8a08\u7b97\u6a5f, \u6559\u80b2, IT \u96fb\u8166\u73ed,\u96fb\u8166\u88dc\u7fd2\uff0c \u96fb\u8166\u73ed\uff0c \u5bb6\u6559\uff0c \u79c1\u4eba\u8001\u5e2b\uff0c \u8cc7\u8a0a\u6280\u8853\uff0c \u7a0b\u5e8f\u8a2d\u8a08\uff0c \u96fb\u5b50\u8a08\u7b97\u6a5f\uff0c \u904a\u6232\uff0c \u860b\u679c\uff0c \u96fb\u5f71\uff0c \u8a08\u7b97\u6a5f\uff0c\u7de8\u78bc\uff0c Java\uff0c C\/C++\uff0c JavaScript\uff0c PHP\uff0c HTML\uff0c CSS\uff0c MySQL\uff0c mobile\uff0c Android\uff0c \u52d5\u6f2b\uff0c Python\uff0c teacher\uff0c \u88dc\u7fd2\uff0c \u96fb\u8166\u88dc\u7fd2 \u8cc7\u8a0a, \u7535\u5b50\u8ba1\u7b97\u673a, IT ,Game, apple, movie, Computer,student,Java,\u6559\u80b2, ,\u5b66\u751f, \u5b66\u4e60, learn, \u6559\u5b66,  Android, apple,anime, animation, \u4fe1\u606f\u6280\u672f, \u7a0b\u5e8f\u8bbe\u8ba1, \u79fb\u52a8\u7535\u8bdd, \u8cc7\u8a0a\u79d1\u6280,Game, Jeu, Juego,Call Of Duty ,\u4f7f\u547d\u53ec\u559a , \u6e38\u620f, \u7535\u5b50\u6e38\u620f,, \u591a\u4eba\u7535\u5b50\u6e38\u620f, \u7f51\u7edc\u6e38\u620f\uff0conline\uff0conline game, \u624b\u673a\u6e38\u620f, mobile \\\"><\/p>\n<div>\n<p>In this tutorial, you\u2019ll learn various techniques to catch multiple exceptions with Python. To begin with, you\u2019ll review Python\u2019s <strong>exception handling<\/strong> mechanism before diving deeper and learning how to identify what you\u2019ve caught, sometimes ignore what you\u2019ve caught, and even catch lots of exceptions.<\/p>\n<p>Python raises an <a href=\"https:\/\/realpython.com\/python-exceptions\/\">exception<\/a> when your code encounters an occasional but not unexpected error. For example, this will occur if you try to read a missing file. Because you\u2019re aware that such exceptions may occur, you should write code to deal with, or <strong>handle<\/strong>, them. In contrast, a <strong>bug<\/strong> happens when your code does something illogical, like a miscalculation. Bugs should be fixed, not handled. This is why <a href=\"https:\/\/realpython.com\/python-debug-idle\/\">debugging your code<\/a> is important.<\/p>\n<p>When your Python program encounters an error and raises an exception, your code will probably crash, but not before providing a message within a <a href=\"https:\/\/realpython.com\/python-traceback\/\">traceback<\/a> indicating what the problem is:<\/p>\n<div class=\"highlight python repl\"><span class=\"repl-toggle\" title=\"Toggle REPL prompts and output\">&gt;&gt;&gt;<\/span><\/p>\n<pre><span><\/span><code><span class=\"gp\">&gt;&gt;&gt; <\/span><span class=\"mi\">12<\/span> <span class=\"o\">\/<\/span> <span class=\"s2\">\"five\"<\/span>\n<span class=\"gt\">Traceback (most recent call last):<\/span>\n<span class=\"w\">  <\/span><span class=\"c\">...<\/span>\n<span class=\"gr\">TypeError<\/span>: <span class=\"n\">unsupported operand type(s) for \/: 'int' and 'str'<\/span>\n<\/code><\/pre>\n<\/div>\n<p>Here, you\u2019ve tried to divide a <a href=\"https:\/\/realpython.com\/python-numbers\/\">number<\/a> by a <a href=\"https:\/\/realpython.com\/python-strings\/\">string<\/a>. Python can\u2019t do this, so it raises a <a href=\"https:\/\/realpython.com\/python-traceback\/#typeerror\"><code>TypeError<\/code><\/a> exception. It then shows a traceback reminding you that the division operator doesn\u2019t work with strings.<\/p>\n<p>To allow you to take action when an error occurs, you implement <a href=\"https:\/\/realpython.com\/python-raise-exception\/#handling-exceptional-situations-in-python\">exception handling<\/a> by writing code to <strong>catch<\/strong> and deal with exceptions. Better this than your code crashing and scaring your user. To handle exceptions, you use the <a href=\"https:\/\/docs.python.org\/3\/reference\/compound_stmts.html#the-try-statement\"><code>try<\/code><\/a> statement. This allows you to monitor code for exceptions and take action should they occur.<\/p>\n<p>Most <code>try<\/code> statements use <a href=\"https:\/\/realpython.com\/python-exceptions\/#the-try-and-except-block-handling-exceptions\"><code>try<\/code> \u2026 <code>except<\/code><\/a> blocks as follows:<\/p>\n<ul>\n<li>\n<p>The <code>try<\/code> block contains the code that you wish to monitor for exceptions. Any exceptions raised within <code>try<\/code> will be eligible for handling.<\/p>\n<\/li>\n<li>\n<p>One or more <code>except<\/code> blocks then follow <code>try<\/code>. These are where you define the code that will run when exceptions occur. In your code, any raised exceptions trigger the associated <code>except<\/code> clause. Note that where you have multiple <code>except<\/code> clauses, your program will run only the <em>first one<\/em> that triggers and then ignore the rest.<\/p>\n<\/li>\n<\/ul>\n<p>To learn how this works, you write a <code>try<\/code> block to monitor three lines of code. You include two <code>except<\/code> blocks, one each for <a href=\"https:\/\/realpython.com\/python-traceback\/#valueerror\"><code>ValueError<\/code><\/a> and <a href=\"https:\/\/docs.python.org\/3\/library\/exceptions.html#ZeroDivisionError\"><code>ZeroDivisionError<\/code><\/a> exceptions, to handle them should they occur:<\/p>\n<div class=\"highlight python\">\n<pre><span><\/span><code><span class=\"c1\"># handler_statement.py<\/span>\n\n<span class=\"k\">try<\/span><span class=\"p\">:<\/span>\n    <span class=\"n\">first<\/span> <span class=\"o\">=<\/span> <span class=\"nb\">float<\/span><span class=\"p\">(<\/span><span class=\"nb\">input<\/span><span class=\"p\">(<\/span><span class=\"s2\">\"What is your first number? \"<\/span><span class=\"p\">))<\/span>\n    <span class=\"n\">second<\/span> <span class=\"o\">=<\/span> <span class=\"nb\">float<\/span><span class=\"p\">(<\/span><span class=\"nb\">input<\/span><span class=\"p\">(<\/span><span class=\"s2\">\"What is your second number? \"<\/span><span class=\"p\">))<\/span>\n    <span class=\"nb\">print<\/span><span class=\"p\">(<\/span><span class=\"sa\">f<\/span><span class=\"s2\">\"<\/span><span class=\"si\">{<\/span><span class=\"n\">first<\/span><span class=\"si\">}<\/span><span class=\"s2\"> divided by <\/span><span class=\"si\">{<\/span><span class=\"n\">second<\/span><span class=\"si\">}<\/span><span class=\"s2\"> is <\/span><span class=\"si\">{<\/span><span class=\"n\">first<\/span><span class=\"w\"> <\/span><span class=\"o\">\/<\/span><span class=\"w\"> <\/span><span class=\"n\">second<\/span><span class=\"si\">}<\/span><span class=\"s2\">\"<\/span><span class=\"p\">)<\/span>\n<span class=\"k\">except<\/span> <span class=\"ne\">ValueError<\/span><span class=\"p\">:<\/span>\n    <span class=\"nb\">print<\/span><span class=\"p\">(<\/span><span class=\"s2\">\"You must enter a number\"<\/span><span class=\"p\">)<\/span>\n<span class=\"k\">except<\/span> <span class=\"ne\">ZeroDivisionError<\/span><span class=\"p\">:<\/span>\n    <span class=\"nb\">print<\/span><span class=\"p\">(<\/span><span class=\"s2\">\"You can't divide by zero\"<\/span><span class=\"p\">)<\/span>\n<\/code><\/pre>\n<\/div>\n<p>The code that you\u2019re monitoring asks the user to enter both numbers and then prints the division. You\u2019ll cause a <code>ValueError<\/code> if you don\u2019t enter a number in the first two lines of code. When the <code>float()<\/code> function tries to convert your input into a <code>float<\/code>, a <code>ValueError<\/code> occurs if this isn\u2019t possible. A <code>ZeroDivisionError<\/code> occurs if you enter <code>0<\/code> as the second number. When the <code>print()<\/code> function attempts to divide by zero, you get a <code>ZeroDivisionError<\/code>. <\/p>\n<p>Having written the above code, you then test each of the control flows. To do this, you first provide perfectly valid data, then provide a <code>string<\/code> for the second number, and finally provide a <code>0<\/code> for the second number: <\/p>\n<div class=\"highlight sh\">\n<pre><span><\/span><code><span class=\"gp\">$ <\/span>python<span class=\"w\"> <\/span>handler_statement.py\n<span class=\"go\">What is your first number? 10<\/span>\n<span class=\"go\">What is your second number? 5<\/span>\n<span class=\"go\">10.0 divided by 5.0 is 2.0<\/span>\n\n<span class=\"gp\">$ <\/span>python<span class=\"w\"> <\/span>handler_statement.py\n<span class=\"go\">What is your first number? 10<\/span>\n<span class=\"go\">What is your second number? \"five\"<\/span>\n<span class=\"go\">You must enter a number<\/span>\n\n<span class=\"gp\">$ <\/span>python<span class=\"w\"> <\/span>handler_statement.py\n<span class=\"go\">What is your first number? 10<\/span>\n<span class=\"go\">What is your second number? 0<\/span>\n<span class=\"go\">You can't divide by zero<\/span>\n<\/code><\/pre>\n<\/div>\n<p>The good news is that your code never crashes. This is because your code has successfully handled the exceptions.<\/p>\n<p>First, you provided acceptable data. When you look at the output, you can see that the program flows only through <code>try<\/code>. You haven\u2019t invoked any of the <code>except<\/code> clauses because Python hasn\u2019t raised any exceptions.<\/p>\n<p>You then cause a <code>ValueError<\/code> by entering a string. This happens because the <a href=\"https:\/\/realpython.com\/python-numbers\/#floating-point-numbers\"><code>float()<\/code><\/a> function can\u2019t convert your <code>\"five\"<\/code> into a <code>float<\/code>. Your program flow now becomes <code>try<\/code> then <code>except ValueError<\/code>. Despite raising a <code>ValueError<\/code>, your code has handled it gracefully. Your users will no longer experience a worrying crash.<\/p>\n<p>In your final test run, you try to divide by <code>0<\/code>. This time, you cause a <code>ZeroDivisionError<\/code> because Python doesn\u2019t like your enthusiasm for <a href=\"https:\/\/en.wikipedia.org\/wiki\/Division_by_zero\">Riemann spheres and infinity<\/a>. This time, the program flow is <code>try<\/code> then <code>except ZeroDivisionError<\/code>. Again, your code has handled your exception gracefully. Most of your users will be happy with this, though the mathematicians may be disappointed.<\/p>\n<p>After the error handling is complete, your program\u2019s flow would usually continue with any code beyond the <code>try<\/code> statement. In this case, there\u2019s none, so the program simply ends. <\/p>\n<p>As an exercise, you might like to try entering a string as the first input and a number as the second. Can you predict what will happen before you try it out? <\/p>\n<div class=\"alert alert-primary\" role=\"alert\">\n<p><strong>Note:<\/strong> Your code catches only <code>ZeroDivisionError<\/code> or <code>ValueError<\/code> exceptions. Should any others be raised, it\u2019ll crash as before. You could get around this by creating a final <code>except Exception<\/code> clause to catch all other exceptions. However, this is bad practice because you might catch exceptions that you didn\u2019t anticipate. It\u2019s better to catch exceptions explicitly and customize your handling of them.<\/p>\n<\/div>\n<p>Up to this point, you\u2019ve reviewed how to catch exceptions individually using the <code>try<\/code> statement. In the remainder of this tutorial, you\u2019ll learn about ways that you can catch multiple exceptions. Time to dive a bit deeper.<\/p>\n<div class=\"alert alert-warning\" role=\"alert\">\n<p><strong markdown=\"1\">Get Your Code:<\/strong> <a href=\"https:\/\/realpython.com\/bonus\/python-catch-multiple-exceptions-code\/\" class=\"alert-link\" data-toggle=\"modal\" data- data-focus=\"false\" markdown=\"1\">Click here to download the sample code<\/a> that shows you how to catch multiple exceptions in Python.<\/p>\n<\/div>\n<h2 id=\"how-to-catch-one-of-several-possible-python-exceptions\">How to Catch One of Several Possible Python Exceptions<a class=\"headerlink\" href=\"https:\/\/realpython.com\/python-catch-multiple-exceptions\/#how-to-catch-one-of-several-possible-python-exceptions\" title=\"Permanent link\"><\/a><\/h2>\n<p>Catching individual exceptions in separate <code>except<\/code> clauses is the way to go if you need to perform different handling actions on the different exceptions being caught. If you find that you\u2019re performing the <em>same<\/em> actions in response to different exceptions, then you can produce simpler, more readable code by handling multiple exceptions in a single <code>except<\/code> clause. To do this, you specify the exceptions as a <a href=\"https:\/\/realpython.com\/python-lists-tuples\/#python-tuples\">tuple<\/a> within the <code>except<\/code> statement.<\/p>\n<p>Suppose you now like the idea of your earlier code being able to handle both exceptions in a single line. To do this, you decide to rewrite your code as follows:<\/p>\n<\/div>\n<h2><a href=\"https:\/\/realpython.com\/python-catch-multiple-exceptions\/?utm_source=realpython&#038;utm_medium=rss\">Read the full article at https:\/\/realpython.com\/python-catch-multiple-exceptions\/ \u00bb<\/a><\/h2>\n<hr \/>\n<p><em>[ Improve Your Python With ? Python Tricks ? \u2013 Get a short &amp; sweet Python Trick delivered to your inbox every couple of days. <a href=\"https:\/\/realpython.com\/python-tricks\/?utm_source=realpython&amp;utm_medium=rss&amp;utm_campaign=footer\">&gt;&gt; Click here to learn more and see examples<\/a> ]<\/em><\/p>\n\n<p class=\"syndicated-attribution\"><figure class= \\\"wp-block-image alignnone \\\"><img src= \\\"http:\/\/itteacheritfreelance.hk\/test\/wordpress\/wp-content\/uploads\/2016\/05\/logo2-2.png\\\" alt=\\\"IT\u96fb\u8166\u88dc\u7fd2 java\u88dc\u7fd2 \u70ba\u5927\u5bb6\u914d\u5c0d\u96fb\u8166\u88dc\u7fd2,IT freelance, \u79c1\u4eba\u8001\u5e2b, PHP\u88dc\u7fd2,CSS\u88dc\u7fd2,XML,Java\u88dc\u7fd2,MySQL\u88dc\u7fd2,graphic design\u88dc\u7fd2,\u4e2d\u5c0f\u5b78ICT\u88dc\u7fd2,\u4e00\u5c0d\u4e00\u79c1\u4eba\u88dc\u7fd2\u548cFreelance\u81ea\u7531\u5de5\u4f5c\u914d\u5c0d\u3002\\\"\/><figcaption>\u7acb\u523b\u8a3b\u518a\u53ca\u5831\u540d\u96fb\u8166\u88dc\u7fd2\u8ab2\u7a0b\u5427!<\/figcaption><\/figure>\r\n<\/br>Find A Teacher Form:\r\n<\/br>https:\/\/docs.google.com\/forms\/d\/1vREBnX5n262umf4wU5U2pyTwvk9O-JrAgblA-wH9GFQ\/viewform?edit_requested=true#responses\r\n<\/br><\/br>Email:\r\n<\/br>public1989two@gmail.com<br><br><br><br><br><br><br>\r\n<a href=www.itsec.hk style=color:#FFFFFF;>www.itsec.hk<\/a><br>\r\n<a href=\\\"www.itsec.vip\\\" style=color:#FFFFFF;>www.itsec.vip<\/a><br>\r\n<a href=\\\"www.itseceu.uk\\\" style=color:#FFFFFF;>www.itseceu.uk<\/a><br><\/p>","protected":false},"excerpt":{"rendered":"<div class=\"mh-excerpt\"><p>In this how-to tutorial, you&#8217;ll learn different ways of catching multiple Python exceptions. You&#8217;ll review the standard way of using a tuple in the except clause, but also expand your knowledge by exploring some other techniques, such as suppressing exceptions and using exception groups.<\/p>\n<\/div>","protected":false},"author":2055,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"slim_seo":{"title":"How to Catch Multiple Exceptions in Python - ITTeacherITFreelance.hk","description":"In this how-to tutorial, you'll learn different ways of catching multiple Python exceptions. You'll review the standard way of using a tuple in the except claus"},"footnotes":""},"categories":[10700],"tags":[],"_links":{"self":[{"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/posts\/329494"}],"collection":[{"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/users\/2055"}],"replies":[{"embeddable":true,"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/comments?post=329494"}],"version-history":[{"count":1,"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/posts\/329494\/revisions"}],"predecessor-version":[{"id":329495,"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/posts\/329494\/revisions\/329495"}],"wp:attachment":[{"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/media?parent=329494"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/categories?post=329494"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/tags?post=329494"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}