{"id":2484,"date":"2020-01-13T19:57:46","date_gmt":"2020-01-13T19:57:46","guid":{"rendered":"https:\/\/www.askpython.com\/?p=2484"},"modified":"2022-08-06T13:10:17","modified_gmt":"2022-08-06T13:10:17","slug":"python-catch-multiple-exceptions","status":"publish","type":"post","link":"https:\/\/www.askpython.com\/python\/examples\/python-catch-multiple-exceptions","title":{"rendered":"Python &#8211; Catch Multiple Exceptions"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">Python always operates on an Exception based model. That is, any errors during the program execution are passed as Exceptions and returned to the programmer, which may be handled accordingly using <a href=\"https:\/\/www.askpython.com\/python\/python-exception-handling\" class=\"rank-math-link\">Exception Handling<\/a> techniques.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Sometimes, it is possible that a process raises more than one possible exception, depending on the flow of control. Thus, we may need to catch <em>Multiple Exceptions<\/em> for this program\/function.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Let us understand how we can handle multiple exceptions in Python.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Catch Multiple Exceptions<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Python allows us to handle multiple exceptions in 2 ways:<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Using Multiple Except Blocks<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">We can catch multiple exceptions by sequentially writing down <code>except<\/code> blocks for all those exceptions.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The pseudo-code looks like this:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\ntry:\n    pass\nexcept Exception1:\n    pass\nexcept Exception2:\n    pass\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">Let us understand this way of handling through an example.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Consider the below function which tries to add all items of a List using the <code>+<\/code> operator, and also checks if any Integer item is less than 200. Since addition\/concatenation can also fail if the types are different, there are multiple Exceptions possible.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\ninput_list_1 = &#x5B;&#039;Hello&#039;, &#039; from&#039;, 123, 456, &#039; AskPython&#039;]\ninput_list_2 = &#x5B;123, 456, &#039; AskPython&#039;]\n\ndef add_list(ip):\n    # Adds all items of a list\n    # Will raise ValueError if any integer item &gt; 200\n    # and will raise TypeError if addition operands are of different types\n    if isinstance(ip, list):\n        result = &#039;&#039; if isinstance(ip&#x5B;0], str) else 0\n        for item in ip:\n            if isinstance(item, int) and item &gt; 200:\n                raise ValueError(&#039;Integer Item has to be &lt;= 200&#039;)\n            result = result + item\n        return result\n    else:\n        return None\n\ntry:\n    # Will raise TypeError\n    res = add_list(input_list_1)\n    print(res)\nexcept TypeError as te:\n    print(type(te), te)\nexcept ValueError as ve:\n    print(type(ve), ve)\n\ntry:\n    # Will raise ValueError since 456 &gt; 200\n    res = add_list(input_list_2)\n    print(res)\nexcept TypeError as te:\n    print(type(te), te)\nexcept ValueError as ve:\n    print(type(ve), ve)\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">The function is run on two lists, to show that multiple exceptions can be raised from a single function.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Output<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n&lt;class &#039;TypeError&#039;&gt; can only concatenate str (not &quot;int&quot;) to str\n&lt;class &#039;ValueError&#039;&gt; Integer Item has to be &lt;= 200\n<\/pre><\/div>\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">Using a Single Except Block<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">We can also catch multiple exceptions in a single <code>except<\/code> block, if you want the same behavior for all those exceptions.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This can avoid unnecessary duplication of code and can save the programmer&#8217;s time if the output is the same for multiple exceptions.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Pseudo-code for the same:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\ntry:\n    pass\nexcept (Exception1, Exception2) as e:\n    pass\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">Let us modify the <code>main<\/code> block using a single <code>except<\/code> block for multiple exceptions.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\ntry:\n    res = add_list(input_list_1)\n    print(res)\nexcept (TypeError, ValueError) as err:\n    print(type(err), err)\n\ntry:\n    res = add_list(input_list_2)\n    print(res)\nexcept (TypeError, ValueError) as err:\n    print(type(err), err)\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">The output will remain the same:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n&lt;class &#039;TypeError&#039;&gt; can only concatenate str (not &quot;int&quot;) to str\n&lt;class &#039;ValueError&#039;&gt; Integer Item has to be &lt;= 200\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\"><strong>NOTE<\/strong>: The multiple exceptions can be any combination of in-built exceptions and <a class=\"rank-math-link rank-math-link\" href=\"https:\/\/www.askpython.com\/python\/python-custom-exceptions\">custom exceptions<\/a>.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">In this article, we learned the two ways of handling multiple exceptions in Python, using multiple sequential <code>except<\/code> blocks, and also using a single <code>except<\/code> block to reduce duplication of code.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">References<\/h2>\n\n\n\n<ul class=\"wp-block-list\"><li><a href=\"https:\/\/stackoverflow.com\/questions\/38871016\/how-to-handle-multiple-exceptions\" class=\"rank-math-link\" target=\"_blank\" rel=\"noopener\">StackOverflow question on Multiple Exceptions<\/a><\/li><\/ul>\n\n\n\n<ul class=\"wp-block-list\"><li>JournalDev article on Multiple Exception Handling<\/li><\/ul>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n","protected":false},"excerpt":{"rendered":"<p>Python always operates on an Exception based model. That is, any errors during the program execution are passed as Exceptions and returned to the programmer, which may be handled accordingly using Exception Handling techniques. Sometimes, it is possible that a process raises more than one possible exception, depending on the flow of control. Thus, we [&hellip;]<\/p>\n","protected":false},"author":7,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[9],"tags":[],"class_list":["post-2484","post","type-post","status-publish","format-standard","hentry","category-examples"],"blocksy_meta":[],"_links":{"self":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/2484","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/users\/7"}],"replies":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/comments?post=2484"}],"version-history":[{"count":0,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/2484\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media?parent=2484"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/categories?post=2484"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/tags?post=2484"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}