{"id":3049,"date":"2021-11-27T02:57:54","date_gmt":"2021-11-27T02:57:54","guid":{"rendered":"https:\/\/www.pythontutorial.net\/?page_id=3049"},"modified":"2025-03-28T03:40:22","modified_gmt":"2025-03-28T03:40:22","slug":"python-exceptions","status":"publish","type":"page","link":"https:\/\/www.pythontutorial.net\/python-oop\/python-exceptions\/","title":{"rendered":"Python Exceptions"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: in this tutorial, you&#8217;ll learn about the Python exceptions and how to handle them gracefully in programs.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='introduction-to-python-exceptions'>Introduction to Python exceptions <a href=\"#introduction-to-python-exceptions\" class=\"anchor\" id=\"introduction-to-python-exceptions\" title=\"Anchor for Introduction to Python exceptions\">#<\/a><\/h2>\n\n\n\n<p>In Python, exceptions are objects of the exception <a href=\"https:\/\/www.pythontutorial.net\/python-oop\/python-class\/\">classes<\/a>. All exception classes are the subclasses of the <code>BaseException<\/code> class. <\/p>\n\n\n\n<p>However, almost all built-in exception classes inherit from the <code>Exception<\/code> class, which is the subclass of the <code>BaseException<\/code> class:<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img decoding=\"async\" src=\"https:\/\/www.pythontutorial.net\/wp-content\/uploads\/2021\/11\/python-exceptions.svg\" alt=\"python exceptions\" class=\"wp-image-3112\"\/><\/figure>\n<\/div>\n\n\n<p>This page shows a complete <a href=\"https:\/\/docs.python.org\/3\/library\/exceptions.html#exception-hierarchy\" target=\"_blank\" rel=\"noreferrer noopener\">class hierarchy for built-in exceptions in Python<\/a>.<\/p>\n\n\n\n<p>The following example defines a list of three elements and attempts to access the fourth one:<\/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\">colors = &#91;<span class=\"hljs-string\">'red'<\/span>, <span class=\"hljs-string\">'green'<\/span>, <span class=\"hljs-string\">'blue'<\/span>]\n\nprint(colors&#91;<span class=\"hljs-number\">3<\/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>The invalid index caused the <code>IndexError<\/code> exception as expected:<\/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\">IndexError: list index out of range<\/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>When an exception occurs, Python stops the program unless you handle it. To handle an exception, you use the <code><a href=\"https:\/\/www.pythontutorial.net\/python-basics\/python-try-except\/\">try...except<\/a><\/code> statement. For example:<\/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\">colors = &#91;<span class=\"hljs-string\">'red'<\/span>, <span class=\"hljs-string\">'green'<\/span>, <span class=\"hljs-string\">'blue'<\/span>]\n\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(e)\n\n\nprint(<span class=\"hljs-string\">'Continue to run'<\/span>)<\/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><a href=\"https:\/\/www.pythontutorial.net\/playground\/?q=Y29sb3JzID0gWydyZWQnLCAnZ3JlZW4nLCAnYmx1ZSddCgp0cnk6CiAgICBwcmludChjb2xvcnNbM10pCmV4Y2VwdCBJbmRleEVycm9yIGFzIGU6CiAgICBwcmludChlKQoKCnByaW50KCdDb250aW51ZSB0byBydW4nKQ%3D%3D\" target=\"_blank\" rel=\"noreferrer noopener\">Try it<\/a><\/p>\n\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"plaintext\" data-shcb-language-slug=\"plaintext\"><span><code class=\"hljs language-plaintext\">&lt;class 'IndexError'&gt; - list index out of range\nContinue to run<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">plaintext<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">plaintext<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>In this example, we use the <code>try...except<\/code> statement to handle the <code>IndexError<\/code> exception. As you can see from the output, the program continues to run after the <code>try...except<\/code> statement.<\/p>\n\n\n\n<p>The <code>IndexError<\/code> class inherits from the <code>LookupError<\/code> class which inherits from the <code>Exception<\/code> class:<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img decoding=\"async\" src=\"https:\/\/www.pythontutorial.net\/wp-content\/uploads\/2021\/11\/python-exception-classes.svg\" alt=\"\" class=\"wp-image-3054\"\/><\/figure>\n<\/div>\n\n\n<p>And you can catch either <code>LookupError<\/code> or <code>Exception<\/code> class when an <code>IndexError<\/code> exception occurs. For example:<\/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\">colors = &#91;<span class=\"hljs-string\">'red'<\/span>, <span class=\"hljs-string\">'green'<\/span>, <span class=\"hljs-string\">'blue'<\/span>]\n\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(e.__class__, <span class=\"hljs-string\">'-'<\/span>, e)\n\nprint(<span class=\"hljs-string\">'Continue to run'<\/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><a href=\"https:\/\/www.pythontutorial.net\/playground\/?q=Y29sb3JzID0gWydyZWQnLCAnZ3JlZW4nLCAnYmx1ZSddCgp0cnk6CiAgICBwcmludChjb2xvcnNbM10pCmV4Y2VwdCBMb29rdXBFcnJvciBhcyBlOgogICAgcHJpbnQoZS5fX2NsYXNzX18sICctJywgZSkKCnByaW50KCdDb250aW51ZSB0byBydW4nKQ%3D%3D\" target=\"_blank\" rel=\"noreferrer noopener\">Try it<\/a><\/p>\n\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-6\" data-shcb-language-name=\"plaintext\" data-shcb-language-slug=\"plaintext\"><span><code class=\"hljs language-plaintext\">&lt;class 'IndexError'&gt; - list index out of range\nContinue to run<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-6\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">plaintext<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">plaintext<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>In this example, the exception is still <code>IndexError<\/code> even though we catch the <code>LookupError<\/code> exception. Therefore, when you handle an exception, the exception handler will catch the exception type you specify and any of its subclasses.<\/p>\n\n\n\n<p>The program runs the same if you use the <code>Exception<\/code> class instead of the <code>LookupError<\/code> class:<\/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\">colors = &#91;<span class=\"hljs-string\">'red'<\/span>, <span class=\"hljs-string\">'green'<\/span>, <span class=\"hljs-string\">'blue'<\/span>]\n\n<span class=\"hljs-keyword\">try<\/span>:\n    print(colors&#91;<span class=\"hljs-number\">3<\/span>])\n<span class=\"hljs-keyword\">except<\/span> Exception <span class=\"hljs-keyword\">as<\/span> e:\n    print(e.__class__, <span class=\"hljs-string\">'-'<\/span>, e)\n\nprint(<span class=\"hljs-string\">'Continue to run'<\/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><a href=\"https:\/\/www.pythontutorial.net\/playground\/?q=Y29sb3JzID0gWydyZWQnLCAnZ3JlZW4nLCAnYmx1ZSddCgp0cnk6CiAgICBwcmludChjb2xvcnNbM10pCmV4Y2VwdCBFeGNlcHRpb24gYXMgZToKICAgIHByaW50KGUuX19jbGFzc19fLCAnLScsIGUpCgpwcmludCgnQ29udGludWUgdG8gcnVuJyk%3D\" target=\"_blank\" rel=\"noreferrer noopener\">Try it<\/a><\/p>\n\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-8\" data-shcb-language-name=\"plaintext\" data-shcb-language-slug=\"plaintext\"><span><code class=\"hljs language-plaintext\">&lt;class 'IndexError'&gt; - list index out of range\nContinue to run<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-8\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">plaintext<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">plaintext<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>In practice, you should catch the exceptions as specific as possible so that you know how to deal with each exception in a specific way.<\/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 example defines a <code>division<\/code> function that returns the result of a is divided by b:<\/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-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">division<\/span><span class=\"hljs-params\">(a, b)<\/span>:<\/span>\n    <span class=\"hljs-keyword\">return<\/span> a \/ b\n\n\nc = division(<span class=\"hljs-number\">10<\/span>, <span class=\"hljs-number\">0<\/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>Output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-10\" data-shcb-language-name=\"plaintext\" data-shcb-language-slug=\"plaintext\"><span><code class=\"hljs language-plaintext\">ZeroDivisionError: division by zero<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-10\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">plaintext<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">plaintext<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>In this example, if b is zero, the <code>ZeroDivisionError<\/code> exception will occur. To handle the <code>ZeroDivisionError<\/code> exception, you use the <code>try...except<\/code> statement as follows:<\/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\"><span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">division<\/span><span class=\"hljs-params\">(a, b)<\/span>:<\/span>\n    <span class=\"hljs-keyword\">try<\/span>:\n        <span class=\"hljs-keyword\">return<\/span> {\n            <span class=\"hljs-string\">'success'<\/span>: <span class=\"hljs-literal\">True<\/span>,\n            <span class=\"hljs-string\">'message'<\/span>: <span class=\"hljs-string\">'OK'<\/span>,\n            <span class=\"hljs-string\">'result'<\/span>: a \/ b\n        }\n    <span class=\"hljs-keyword\">except<\/span> ZeroDivisionError <span class=\"hljs-keyword\">as<\/span> e:\n        <span class=\"hljs-keyword\">return<\/span> {\n            <span class=\"hljs-string\">'success'<\/span>: <span class=\"hljs-literal\">False<\/span>,\n            <span class=\"hljs-string\">'message'<\/span>: <span class=\"hljs-string\">'b cannot be zero'<\/span>,\n            <span class=\"hljs-string\">'result'<\/span>: <span class=\"hljs-literal\">None<\/span>\n        }\n\n\nresult = division(<span class=\"hljs-number\">10<\/span>, <span class=\"hljs-number\">0<\/span>)\nprint(result)<\/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 href=\"https:\/\/www.pythontutorial.net\/playground\/?q=ZGVmIGRpdmlzaW9uKGEsIGIpOgogICAgdHJ5OgogICAgICAgIHJldHVybiB7CiAgICAgICAgICAgICdzdWNjZXNzJzogVHJ1ZSwKICAgICAgICAgICAgJ21lc3NhZ2UnOiAnT0snLAogICAgICAgICAgICAncmVzdWx0JzogYSAvIGIKICAgICAgICB9CiAgICBleGNlcHQgWmVyb0RpdmlzaW9uRXJyb3IgYXMgZToKICAgICAgICByZXR1cm4gewogICAgICAgICAgICAnc3VjY2Vzcyc6IEZhbHNlLAogICAgICAgICAgICAnbWVzc2FnZSc6ICdiIGNhbm5vdCBiZSB6ZXJvJywKICAgICAgICAgICAgJ3Jlc3VsdCc6IE5vbmUKICAgICAgICB9CgoKcmVzdWx0ID0gZGl2aXNpb24oMTAsIDApCnByaW50KHJlc3VsdCk%3D\" target=\"_blank\" rel=\"noreferrer noopener\">Try it<\/a><\/p>\n\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-12\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">{<span class=\"hljs-string\">'success'<\/span>: <span class=\"hljs-keyword\">False<\/span>, <span class=\"hljs-string\">'message'<\/span>: <span class=\"hljs-string\">'b cannot be zero'<\/span>, <span class=\"hljs-string\">'result'<\/span>: None}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-12\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>In this example, the function returns a dictionary that has three elements:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>success<\/code> is a boolean value that indicates whethere the operation is successful or not.<\/li>\n\n\n\n<li><code>message<\/code> indicates the error or success message.<\/li>\n\n\n\n<li><code>result<\/code> stores the result of a \/ b or <code>None<\/code> if b is zero.<\/li>\n<\/ul>\n\n\n\n<p>The following shows the output if the <code>ZeroDivisionError<\/code> occurs:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-13\" data-shcb-language-name=\"plaintext\" data-shcb-language-slug=\"plaintext\"><span><code class=\"hljs language-plaintext\">{'success': False, 'message': 'b cannot be zero', 'result': None}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-13\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">plaintext<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">plaintext<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Now, if you don&#8217;t catch the <code>ZeroDivisionError<\/code> exception but the more general exception like <code>Exception<\/code> class:<\/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-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">division<\/span><span class=\"hljs-params\">(a, b)<\/span>:<\/span>\n    <span class=\"hljs-keyword\">try<\/span>:\n        <span class=\"hljs-keyword\">return<\/span> {\n            <span class=\"hljs-string\">'success'<\/span>: <span class=\"hljs-literal\">True<\/span>,\n            <span class=\"hljs-string\">'message'<\/span>: <span class=\"hljs-string\">'OK'<\/span>,\n            <span class=\"hljs-string\">'result'<\/span>: a \/ b\n        }\n    <span class=\"hljs-keyword\">except<\/span> Exception <span class=\"hljs-keyword\">as<\/span> e:\n        <span class=\"hljs-keyword\">return<\/span> {\n            <span class=\"hljs-string\">'success'<\/span>: <span class=\"hljs-literal\">False<\/span>,\n            <span class=\"hljs-string\">'message'<\/span>: <span class=\"hljs-string\">'b cannot be zero'<\/span>,\n            <span class=\"hljs-string\">'result'<\/span>: <span class=\"hljs-literal\">None<\/span>\n        }\n\n\nresult = division(<span class=\"hljs-number\">10<\/span>, <span class=\"hljs-number\">0<\/span>)\nprint(result)<\/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><a href=\"https:\/\/www.pythontutorial.net\/playground\/?q=ZGVmIGRpdmlzaW9uKGEsIGIpOgogICAgdHJ5OgogICAgICAgIHJldHVybiB7CiAgICAgICAgICAgICdzdWNjZXNzJzogVHJ1ZSwKICAgICAgICAgICAgJ21lc3NhZ2UnOiAnT0snLAogICAgICAgICAgICAncmVzdWx0JzogYSAvIGIKICAgICAgICB9CiAgICBleGNlcHQgRXhjZXB0aW9uIGFzIGU6CiAgICAgICAgcmV0dXJuIHsKICAgICAgICAgICAgJ3N1Y2Nlc3MnOiBGYWxzZSwKICAgICAgICAgICAgJ21lc3NhZ2UnOiAnYiBjYW5ub3QgYmUgemVybycsCiAgICAgICAgICAgICdyZXN1bHQnOiBOb25lCiAgICAgICAgfQoKCnJlc3VsdCA9IGRpdmlzaW9uKDEwLCAwKQpwcmludChyZXN1bHQp\" target=\"_blank\" rel=\"noreferrer noopener\">Try it<\/a><\/p>\n\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-15\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">{<span class=\"hljs-string\">'success'<\/span>: <span class=\"hljs-keyword\">False<\/span>, <span class=\"hljs-string\">'message'<\/span>: <span class=\"hljs-string\">'b cannot be zero'<\/span>, <span class=\"hljs-string\">'result'<\/span>: None}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-15\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>The program works as before because the <code>try...except<\/code> also catches the exception type that is the subclass of the <code>Exception<\/code> class.<\/p>\n\n\n\n<p>However, if you pass two strings instead of two numbers to the <code>division()<\/code> function, you&#8217;ll get the same message as if the <code>ZeroDivisionError<\/code> exception occurred:<\/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-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">division<\/span><span class=\"hljs-params\">(a, b)<\/span>:<\/span>\n    <span class=\"hljs-keyword\">try<\/span>:\n        <span class=\"hljs-keyword\">return<\/span> {\n            <span class=\"hljs-string\">'success'<\/span>: <span class=\"hljs-literal\">True<\/span>,\n            <span class=\"hljs-string\">'message'<\/span>: <span class=\"hljs-string\">'OK'<\/span>,\n            <span class=\"hljs-string\">'result'<\/span>: a \/ b\n        }\n    <span class=\"hljs-keyword\">except<\/span> Exception <span class=\"hljs-keyword\">as<\/span> e:\n        <span class=\"hljs-keyword\">return<\/span> {\n            <span class=\"hljs-string\">'success'<\/span>: <span class=\"hljs-literal\">False<\/span>,\n            <span class=\"hljs-string\">'message'<\/span>: <span class=\"hljs-string\">'b cannot be zero'<\/span>,\n            <span class=\"hljs-string\">'result'<\/span>: <span class=\"hljs-literal\">None<\/span>\n        }\n\n\nresult = division(<span class=\"hljs-string\">'10'<\/span>, <span class=\"hljs-string\">'2'<\/span>)\nprint(result)<\/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><a href=\"https:\/\/www.pythontutorial.net\/playground\/?q=ZGVmIGRpdmlzaW9uKGEsIGIpOgogICAgdHJ5OgogICAgICAgIHJldHVybiB7CiAgICAgICAgICAgICdzdWNjZXNzJzogVHJ1ZSwKICAgICAgICAgICAgJ21lc3NhZ2UnOiAnT0snLAogICAgICAgICAgICAncmVzdWx0JzogYSAvIGIKICAgICAgICB9CiAgICBleGNlcHQgRXhjZXB0aW9uIGFzIGU6CiAgICAgICAgcmV0dXJuIHsKICAgICAgICAgICAgJ3N1Y2Nlc3MnOiBGYWxzZSwKICAgICAgICAgICAgJ21lc3NhZ2UnOiAnYiBjYW5ub3QgYmUgemVybycsCiAgICAgICAgICAgICdyZXN1bHQnOiBOb25lCiAgICAgICAgfQoKCnJlc3VsdCA9IGRpdmlzaW9uKCcxMCcsICcyJykKcHJpbnQocmVzdWx0KQ%3D%3D\" target=\"_blank\" rel=\"noreferrer noopener\">Try it<\/a><\/p>\n\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-17\" data-shcb-language-name=\"plaintext\" data-shcb-language-slug=\"plaintext\"><span><code class=\"hljs language-plaintext\">{'success': False, 'message': 'b cannot be zero', 'result': None}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-17\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">plaintext<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">plaintext<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>In this example, the exception is not <code>ZeroDivisionError<\/code> but the <code>TypeError<\/code>. However, the code still handles it like the <code>ZeroDivisionError<\/code> exception.<\/p>\n\n\n\n<p>Therefore, you should always handle the exceptions from the most specific to the least specific. For example:<\/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\"><span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">division<\/span><span class=\"hljs-params\">(a, b)<\/span>:<\/span>\n    <span class=\"hljs-keyword\">try<\/span>:\n        <span class=\"hljs-keyword\">return<\/span> {\n            <span class=\"hljs-string\">'success'<\/span>: <span class=\"hljs-literal\">True<\/span>,\n            <span class=\"hljs-string\">'message'<\/span>: <span class=\"hljs-string\">'OK'<\/span>,\n            <span class=\"hljs-string\">'result'<\/span>: a \/ b\n        }\n    <span class=\"hljs-keyword\">except<\/span> TypeError <span class=\"hljs-keyword\">as<\/span> e:\n        <span class=\"hljs-keyword\">return<\/span> {\n            <span class=\"hljs-string\">'success'<\/span>: <span class=\"hljs-literal\">False<\/span>,\n            <span class=\"hljs-string\">'message'<\/span>: <span class=\"hljs-string\">'Both a &amp; b must be numbers'<\/span>,\n            <span class=\"hljs-string\">'result'<\/span>: <span class=\"hljs-literal\">None<\/span>\n        }\n    <span class=\"hljs-keyword\">except<\/span> ZeroDivisionError <span class=\"hljs-keyword\">as<\/span> e:\n        <span class=\"hljs-keyword\">return<\/span> {\n            <span class=\"hljs-string\">'success'<\/span>: <span class=\"hljs-literal\">False<\/span>,\n            <span class=\"hljs-string\">'message'<\/span>: <span class=\"hljs-string\">'b cannot be zero'<\/span>,\n            <span class=\"hljs-string\">'result'<\/span>: <span class=\"hljs-literal\">None<\/span>\n        }\n    <span class=\"hljs-keyword\">except<\/span> Exception <span class=\"hljs-keyword\">as<\/span> e:\n        <span class=\"hljs-keyword\">return<\/span> {\n            <span class=\"hljs-string\">'success'<\/span>: <span class=\"hljs-literal\">False<\/span>,\n            <span class=\"hljs-string\">'message'<\/span>: str(e),\n            <span class=\"hljs-string\">'result'<\/span>: <span class=\"hljs-literal\">None<\/span>\n        }\n\n\nresult = division(<span class=\"hljs-string\">'10'<\/span>, <span class=\"hljs-string\">'2'<\/span>)\nprint(result)<\/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><a href=\"https:\/\/www.pythontutorial.net\/playground\/?q=ZGVmIGRpdmlzaW9uKGEsIGIpOgogICAgdHJ5OgogICAgICAgIHJldHVybiB7CiAgICAgICAgICAgICdzdWNjZXNzJzogVHJ1ZSwKICAgICAgICAgICAgJ21lc3NhZ2UnOiAnT0snLAogICAgICAgICAgICAncmVzdWx0JzogYSAvIGIKICAgICAgICB9CiAgICBleGNlcHQgVHlwZUVycm9yIGFzIGU6CiAgICAgICAgcmV0dXJuIHsKICAgICAgICAgICAgJ3N1Y2Nlc3MnOiBGYWxzZSwKICAgICAgICAgICAgJ21lc3NhZ2UnOiAnQm90aCBhICYgYiBtdXN0IGJlIG51bWJlcnMnLAogICAgICAgICAgICAncmVzdWx0JzogTm9uZQogICAgICAgIH0KICAgIGV4Y2VwdCBaZXJvRGl2aXNpb25FcnJvciBhcyBlOgogICAgICAgIHJldHVybiB7CiAgICAgICAgICAgICdzdWNjZXNzJzogRmFsc2UsCiAgICAgICAgICAgICdtZXNzYWdlJzogJ2IgY2Fubm90IGJlIHplcm8nLAogICAgICAgICAgICAncmVzdWx0JzogTm9uZQogICAgICAgIH0KICAgIGV4Y2VwdCBFeGNlcHRpb24gYXMgZToKICAgICAgICByZXR1cm4gewogICAgICAgICAgICAnc3VjY2Vzcyc6IEZhbHNlLAogICAgICAgICAgICAnbWVzc2FnZSc6IHN0cihlKSwKICAgICAgICAgICAgJ3Jlc3VsdCc6IE5vbmUKICAgICAgICB9CgoKcmVzdWx0ID0gZGl2aXNpb24oJzEwJywgJzInKQpwcmludChyZXN1bHQp\" target=\"_blank\" rel=\"noreferrer noopener\">Try it<\/a><\/p>\n\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-19\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">{<span class=\"hljs-string\">'success'<\/span>: <span class=\"hljs-keyword\">False<\/span>, <span class=\"hljs-string\">'message'<\/span>: <span class=\"hljs-string\">'Both a &amp; b must be numbers'<\/span>, <span class=\"hljs-string\">'result'<\/span>: None}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-19\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>In this example, we catch the <code>TypeError<\/code>, <code>ZeroDivisionError<\/code>, and <code>Exception<\/code> in the order that they appear in the <code>try...except<\/code> statement.<\/p>\n\n\n\n<p>If the code that handles different exceptions are the same, you can group all exceptions into one as follows:<\/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-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">division<\/span><span class=\"hljs-params\">(a, b)<\/span>:<\/span>\n    <span class=\"hljs-keyword\">try<\/span>:\n        <span class=\"hljs-keyword\">return<\/span> {\n            <span class=\"hljs-string\">'success'<\/span>: <span class=\"hljs-literal\">True<\/span>,\n            <span class=\"hljs-string\">'message'<\/span>: <span class=\"hljs-string\">'OK'<\/span>,\n            <span class=\"hljs-string\">'result'<\/span>: a \/ b\n        }\n    <span class=\"hljs-keyword\">except<\/span> (TypeError, ZeroDivisionError, Exception) <span class=\"hljs-keyword\">as<\/span> e:\n        <span class=\"hljs-keyword\">return<\/span> {\n            <span class=\"hljs-string\">'success'<\/span>: <span class=\"hljs-literal\">False<\/span>,\n            <span class=\"hljs-string\">'message'<\/span>: str(e),\n            <span class=\"hljs-string\">'result'<\/span>: <span class=\"hljs-literal\">None<\/span>\n        }\n\n\nresult = division(<span class=\"hljs-number\">10<\/span>, <span class=\"hljs-number\">0<\/span>)\nprint(result)<\/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 href=\"https:\/\/www.pythontutorial.net\/playground\/?q=ZGVmIGRpdmlzaW9uKGEsIGIpOgogICAgdHJ5OgogICAgICAgIHJldHVybiB7CiAgICAgICAgICAgICdzdWNjZXNzJzogVHJ1ZSwKICAgICAgICAgICAgJ21lc3NhZ2UnOiAnT0snLAogICAgICAgICAgICAncmVzdWx0JzogYSAvIGIKICAgICAgICB9CiAgICBleGNlcHQgKFR5cGVFcnJvciwgWmVyb0RpdmlzaW9uRXJyb3IsIEV4Y2VwdGlvbikgYXMgZToKICAgICAgICByZXR1cm4gewogICAgICAgICAgICAnc3VjY2Vzcyc6IEZhbHNlLAogICAgICAgICAgICAnbWVzc2FnZSc6IHN0cihlKSwKICAgICAgICAgICAgJ3Jlc3VsdCc6IE5vbmUKICAgICAgICB9CgoKcmVzdWx0ID0gZGl2aXNpb24oMTAsIDApCnByaW50KHJlc3VsdCk%3D\" target=\"_blank\" rel=\"noreferrer noopener\">Try it<\/a><\/p>\n\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-21\" data-shcb-language-name=\"plaintext\" data-shcb-language-slug=\"plaintext\"><span><code class=\"hljs language-plaintext\">{'success': False, 'message': 'division by zero', 'result': None}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-21\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">plaintext<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">plaintext<\/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>Python exceptions are objects of classes, which are the subclasses of the BaseException class.<\/li>\n\n\n\n<li>Do handle the exception from the most specific to lest specific.<\/li>\n<\/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=\"3049\"\n\t\t\t\tdata-post-url=\"https:\/\/www.pythontutorial.net\/python-oop\/python-exceptions\/\"\n\t\t\t\tdata-post-title=\"Python Exceptions\"\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=\"3049\"\n\t\t\t\tdata-post-url=\"https:\/\/www.pythontutorial.net\/python-oop\/python-exceptions\/\"\n\t\t\t\tdata-post-title=\"Python Exceptions\"\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 about the Python exceptions and how to handle them gracefully in programs.<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":417,"menu_order":45,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-3049","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/3049","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=3049"}],"version-history":[{"count":1,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/3049\/revisions"}],"predecessor-version":[{"id":7184,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/3049\/revisions\/7184"}],"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=3049"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}