{"id":2179,"date":"2020-01-03T10:58:29","date_gmt":"2020-01-03T10:58:29","guid":{"rendered":"https:\/\/www.askpython.com\/?p=2179"},"modified":"2022-08-06T13:09:34","modified_gmt":"2022-08-06T13:09:34","slug":"python-custom-exceptions","status":"publish","type":"post","link":"https:\/\/www.askpython.com\/python\/python-custom-exceptions","title":{"rendered":"Python Custom Exceptions"},"content":{"rendered":"\n<p>An Exception is raised whenever there is an error encountered, and it signifies that something went wrong with the program. By default, there are many exceptions that the language defines for us, such as <code>TypeError<\/code> when the wrong type is passed. In this article, we shall look at how we can create our own Custom Exceptions in Python.<\/p>\n\n\n\n<p>But before we take a look at how custom exceptions are implemented, let us find out how we could raise different types of 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\">Raise Exceptions<\/h2>\n\n\n\n<p>Python allows the programmer to raise an Exception manually using the <code>raise<\/code> keyword.<\/p>\n\n\n\n<p>Format: <code>raise ExceptionName<\/code><\/p>\n\n\n\n<p>The below function raises different exceptions depending on the input passed to the function.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\ndef exception_raiser(string):\n    if isinstance(string, int):\n        raise ValueError\n    elif isinstance(string, str):\n        raise IndexError\n    else:\n        raise TypeError\n<\/pre><\/div>\n\n\n<p><strong>Output<\/strong>:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n&gt;&gt;&gt; exception_raiser(123)\nTraceback (most recent call last):\n  File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;\n  File &quot;&lt;stdin&gt;&quot;, line 3, in exception_raiser\nValueError\n&gt;&gt;&gt; exception_raiser(&#039;abc&#039;)\nTraceback (most recent call last):\n  File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;\n  File &quot;&lt;stdin&gt;&quot;, line 5, in exception_raiser\nIndexError\n&gt;&gt;&gt; exception_raiser(&#x5B;123, 456])\nTraceback (most recent call last):\n  File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;\n  File &quot;&lt;stdin&gt;&quot;, line 7, in exception_raiser\nTypeError\n<\/pre><\/div>\n\n\n<p>As you can observe, different types of Exceptions are raised based on the input, at the programmer&#8217;s choice. This allows for good flexibility of Error Handling as well, since we can actively predict why an Exception can be raised.<\/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\">Defining Custom Exceptions<\/h2>\n\n\n\n<p>Similarly, Python also allows us to define our own custom Exceptions. We are in complete control of what this Exception can do, and when it can be raised, using the <code>raise<\/code> keyword. Let us look at how we can define and implement some custom Exceptions.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">1. Create a Custom Exception Class<\/h3>\n\n\n\n<p>We can create a custom Exception class to define the new Exception. Again, the idea behind using a Class is because Python treats everything as a Class. So it doesn&#8217;t seem that outlandish that an Exception can be a class as well!<\/p>\n\n\n\n<p> All Exceptions inherit the parent <code>Exception<\/code> Class, which we shall also inherit when creating our class.<\/p>\n\n\n\n<p>We shall create a Class called <code>MyException<\/code>, which raises an Exception only if the input passed to it is a list and the number of elements in the list is odd.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nclass MyException(Exception):\n\tpass\n\ndef list_check(lst):\n    if len(lst) % 2 != 0:\n        raise MyException\n\n# MyException will not be raised\nlist_check(&#x5B;1, 2, 3, 4])\n\n# MyException will be raised\nlist_check(&#x5B;1, 3, 5])    \n<\/pre><\/div>\n\n\n<p><strong>Output<\/strong>:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nroot@AskPython:~# python3 exceptions.py\nTraceback (most recent call last):\n  File &quot;exceptions.py&quot;, line 12, in &lt;module&gt;\n    list_check(&#x5B;1, 3, 5])\n  File &quot;exceptions.py&quot;, line 6, in list_check\n    raise MyException\n__main__.MyException\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">2. Add a custom Message and Error<\/h3>\n\n\n\n<p>We can add our own error messages and print them to the console for our Custom Exception. This involves passing two other parameters in our <code>MyException<\/code> class, the <code>message<\/code> and <code>error<\/code> parameters.<\/p>\n\n\n\n<p>Let us modify our original code to account for a custom <strong><em>Message<\/em><\/strong> and <em><strong>Error<\/strong><\/em> for our Exception.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nclass MyException(Exception):\n    def __init__(self, message, errors):\n        # Call Exception.__init__(message)\n        # to use the same Message header as the parent class\n        super().__init__(message)\n        self.errors = errors\n        # Display the errors\n        print(&#039;Printing Errors:&#039;)\n        print(errors)\n\ndef list_check(lst):\n    if len(lst) % 2 != 0:\n        raise MyException(&#039;Custom Message&#039;, &#039;Custom Error&#039;)\n\n# MyException will not be raised\nlist_check(&#x5B;1, 2, 3, 4])\n\n# MyException will be raised\nlist_check(&#x5B;1, 3, 5])\n<\/pre><\/div>\n\n\n<p><strong>Output<\/strong>:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nPrinting Errors:\nCustom Error\nTraceback (most recent call last):\n  File &quot;exceptions.py&quot;, line 17, in &lt;module&gt;\n    list_check(&#x5B;1, 3, 5])\n  File &quot;exceptions.py&quot;, line 11, in list_check\n    raise MyException(&#039;Custom Message&#039;, &#039;Custom Error&#039;)\n__main__.MyException: Custom Message\n<\/pre><\/div>\n\n\n<p>We have thus successfully implemented our own Custom Exceptions, including adding custom error messages for debugging purposes! This can be very useful if you are building a Library\/API and another programmer wants to know what exactly went wrong when the custom Exception is raised.<\/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>In this article, we learned how to raise Exceptions using the <code>raise<\/code> keyword, and also build our own Exceptions using a Class and add error messages to our Exception.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">References<\/h2>\n\n\n\n<ul class=\"wp-block-list\"><li>JournalDev article on Custom Exceptions<\/li><li><a href=\"https:\/\/www.askpython.com\/python\/python-exception-handling\" class=\"rank-math-link\">Exception Handling in Python<\/a><\/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>An Exception is raised whenever there is an error encountered, and it signifies that something went wrong with the program. By default, there are many exceptions that the language defines for us, such as TypeError when the wrong type is passed. In this article, we shall look at how we can create our own Custom [&hellip;]<\/p>\n","protected":false},"author":7,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-2179","post","type-post","status-publish","format-standard","hentry","category-python"],"blocksy_meta":[],"_links":{"self":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/2179","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=2179"}],"version-history":[{"count":0,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/2179\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media?parent=2179"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/categories?post=2179"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/tags?post=2179"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}