{"id":9210,"date":"2021-03-24T14:11:10","date_gmt":"2021-03-24T08:41:10","guid":{"rendered":"https:\/\/pynative.com\/?p=9210"},"modified":"2021-03-25T08:26:43","modified_gmt":"2021-03-25T02:56:43","slug":"python-exceptions","status":"publish","type":"post","link":"https:\/\/pynative.com\/python-exceptions\/","title":{"rendered":"Python Exceptions and Errors"},"content":{"rendered":"\n<p>In this article, you will learn error and exception handling in Python. <\/p>\n\n\n\n<p><strong>By the end of the article<\/strong>, you\u2019ll know:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>How to handle exceptions using the try, except, and finally statements<\/li><li>How to create a custom exception<\/li><li>How to raise an exceptions<\/li><li>How to use built-in exception effectively to build robust Python programs<\/li><\/ul>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"845\" height=\"446\" src=\"https:\/\/pynative.com\/wp-content\/uploads\/2021\/03\/python_exception_handling.png\" alt=\"Python Exceptions\" class=\"wp-image-9211\" srcset=\"https:\/\/pynative.com\/wp-content\/uploads\/2021\/03\/python_exception_handling.png 845w, https:\/\/pynative.com\/wp-content\/uploads\/2021\/03\/python_exception_handling-300x158.png 300w, https:\/\/pynative.com\/wp-content\/uploads\/2021\/03\/python_exception_handling-768x405.png 768w\" sizes=\"auto, (max-width: 845px) 100vw, 845px\" \/><figcaption>Python Exceptions<\/figcaption><\/figure><\/div>\n\n\n\n<div class=\"wp-block-yoast-seo-table-of-contents yoast-table-of-contents\"><h2>Table of contents<\/h2><ul><li><a href=\"#h-what-are-exceptions\" data-level=\"2\">What are Exceptions?<\/a><ul><li><a href=\"#h-why-use-exception\" data-level=\"3\">Why use Exception<\/a><\/li><\/ul><\/li><li><a href=\"#h-what-are-errors\" data-level=\"2\">What are Errors?<\/a><ul><li><a href=\"#h-syntax-error\" data-level=\"4\">Syntax error<\/a><\/li><li><a href=\"#h-logical-errors-exception\" data-level=\"4\">Logical errors (Exception)<\/a><\/li><\/ul><\/li><li><a href=\"#h-built-in-exceptions\" data-level=\"2\">Built-in Exceptions<\/a><\/li><li><a href=\"#h-the-try-and-except-block-to-handling-exceptions\" data-level=\"2\">The try and except Block to Handling Exceptions<\/a><ul><li><a href=\"#h-catching-specific-exceptions\" data-level=\"3\">Catching Specific Exceptions <\/a><\/li><li><a href=\"#h-handle-multiple-exceptions-with-a-single-except-clause\" data-level=\"3\">Handle multiple exceptions with a single except clause<\/a><\/li><\/ul><\/li><li><a href=\"#h-using-try-with-finally\" data-level=\"2\">Using try with finally<\/a><\/li><li><a href=\"#h-using-try-with-else-clause\" data-level=\"2\">Using try with else clause<\/a><\/li><li><a href=\"#h-raising-an-exceptions\" data-level=\"2\">Raising an Exceptions<\/a><\/li><li><a href=\"#h-exception-chaining\" data-level=\"2\">Exception Chaining<\/a><\/li><li><a href=\"#h-custom-and-user-defined-exceptions\" data-level=\"2\">Custom and User-defined Exceptions<\/a><ul><li><a href=\"#h-customizing-exception-classes\" data-level=\"3\">Customizing Exception Classes<\/a><\/li><\/ul><\/li><li><a href=\"#h-exception-lifecycle\" data-level=\"2\">Exception Lifecycle<\/a><\/li><li><a href=\"#h-warnings\" data-level=\"2\">Warnings<\/a><\/li><\/ul><\/div>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-what-are-exceptions\">What are Exceptions?<\/h2>\n\n\n\n<p>An exception is an <strong>event that occurs during the execution of programs that disrupt the normal flow of execution<\/strong> (e.g., KeyError Raised when a key is not found in a dictionary.) An exception is a Python object that represents an error..<\/p>\n\n\n\n<p>In Python, an exception is an object derives from the <strong>BaseException<\/strong> class that contains information about an error event that occurred within a method. <strong>Exception object contains<\/strong>:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Error type (exception name)<\/li><li>The state of the program when the error occurred<\/li><li>An error message describes the error event.<\/li><\/ul>\n\n\n\n<p>Exception are useful to indicate different types of possible failure condition.<\/p>\n\n\n\n<p>For example, bellow are the few standard exceptions <\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>FileNotFoundException<\/li><li>ImportError<\/li><li>RuntimeError<\/li><li>NameError<\/li><li>TypeError<\/li><\/ul>\n\n\n\n<p>In Python, we can throw an exception in the try block and catch it in except block.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-why-use-exception\">Why use Exception<\/h3>\n\n\n\n<ul class=\"wp-block-list\"><li><strong>Standardized error handling<\/strong>: Using built-in exceptions or creating a custom exception with a more precise name and description, you can adequately define the error event, which helps you debug the error event.<\/li><li><strong>Cleaner code<\/strong>: Exceptions separate the error-handling code from regular code, which helps us to maintain large code easily.<\/li><li><strong>Robust application<\/strong>: With the help of exceptions, we can develop a solid application, which can handle error event efficiently<\/li><li><strong>Exceptions propagation<\/strong>: By default, the exception propagates the call stack if you don&#8217;t catch it. For example, if any error event occurred in a nested function, you do not have to explicitly catch-and-forward it; automatically, it gets forwarded to the calling function where you can handle it.<\/li><li><strong>Different error types<\/strong>: Either you can use built-in exception or create your custom exception and group them by their generalized parent class, or Differentiate errors by their actual class<\/li><\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-what-are-errors\">What are Errors?<\/h2>\n\n\n\n<p>On the other hand, An <strong>error<\/strong> is an action that is incorrect or inaccurate. For example, syntax error. Due to which the program fails to execute.<\/p>\n\n\n\n<p>The errors can be broadly classified into two types:<\/p>\n\n\n\n<ol class=\"wp-block-list\" id=\"block-ba6cf9c3-58aa-45b6-9788-e2134086a36b\"><li>Syntax errors<\/li><li>Logical errors<\/li><\/ol>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"h-syntax-error\">Syntax error<\/h4>\n\n\n\n<p>The syntax error occurs when we are not following the proper structure or syntax of the language. A syntax error is also known as a <strong>parsing error<\/strong>.<\/p>\n\n\n\n<p>When Python parses the program and finds an incorrect statement it is known as a syntax error. When the parser found a syntax error it exits with an error message without running anything.<\/p>\n\n\n\n<p><strong>Common Python Syntax errors:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Incorrect indentation<\/li><li>Missing colon, comma, or brackets<\/li><li>Putting keywords in the wrong place.<\/li><\/ul>\n\n\n\n<p><strong>Example<\/strong><\/p>\n\n\n<div class=\"hljstoolbar\"><pre id=\"code1\"  class=\"wp-block-code language-python\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">print(<span class=\"hljs-string\">\"Welcome to PYnative\"<\/span>)\n    print(<span class=\"hljs-string\">\"Learn Python with us..\"<\/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><button class=\"hljs-copy-button\" onclick=\"copy_code('code1', this);\"><i class=\"far fa-copy1\" aria-hidden=\"true\"><\/i><\/button><button class=\"hljs-run-button\" onclick=\"run_code('code1');\"><i class=\"far fa-play-circle\" aria-hidden=\"true\"><\/i> Run<\/button><\/div>\n\n\n<p><strong>Output<\/strong><\/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\">print(<span class=\"hljs-string\">\"Learn Python with us..\"<\/span>)\n    ^\nIndentationError: unexpected indent<\/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<h4 class=\"wp-block-heading\" id=\"h-logical-errors-exception\">Logical errors (Exception)<\/h4>\n\n\n\n<p>Even if a statement or expression is syntactically correct, the error that occurs at the runtime is known as a <strong>Logical error or Exception<\/strong>. In other words, <strong>Errors detected during execution are called exceptions<\/strong>.<\/p>\n\n\n\n<p><strong>Common Python Logical errors:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Indenting a block to the wrong level<\/li><li>using the wrong variable name<\/li><li>making a mistake in a boolean expression<\/li><\/ul>\n\n\n\n<p><strong>Example<\/strong><\/p>\n\n\n<div class=\"hljstoolbar\"><pre id=\"code2\"  class=\"wp-block-code language-python\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">a = <span class=\"hljs-number\">10<\/span>\nb = <span class=\"hljs-number\">20<\/span>\nprint(<span class=\"hljs-string\">\"Addition:\"<\/span>, a + c)<\/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><button class=\"hljs-copy-button\" onclick=\"copy_code('code2', this);\"><i class=\"far fa-copy1\" aria-hidden=\"true\"><\/i><\/button><button class=\"hljs-run-button\" onclick=\"run_code('code2');\"><i class=\"far fa-play-circle\" aria-hidden=\"true\"><\/i> Run<\/button><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">print(<span class=\"hljs-string\">\"Addition:\"<\/span>, a + c)\nNameError: name <span class=\"hljs-string\">'c'<\/span> <span class=\"hljs-keyword\">is<\/span> <span class=\"hljs-keyword\">not<\/span> defined<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><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<h2 class=\"wp-block-heading\" id=\"h-built-in-exceptions\">Built-in Exceptions<\/h2>\n\n\n\n<p>The below table shows different built-in exceptions.<\/p>\n\n\n\n<p>Python automatically generates many exceptions and errors. Runtime exceptions, generally a result of programming errors, such as:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Reading a file that is not present<\/li><li>Trying to read data outside the available index of a list<\/li><li>Dividing an integer value by zero<\/li><\/ul>\n\n\n\n<figure class=\"wp-block-table is-style-regular\"><table><thead><tr><th>Exception<\/th><th class=\"has-text-align-left\" data-align=\"left\">Description<\/th><\/tr><\/thead><tbody><tr><td><code>AssertionError<\/code><\/td><td class=\"has-text-align-left\" data-align=\"left\">Raised when an <code>assert<\/code> statement fails.<\/td><\/tr><tr><td><code>AttributeError<\/code><\/td><td class=\"has-text-align-left\" data-align=\"left\">Raised when attribute assignment or reference fails.<\/td><\/tr><tr><td><code>EOFError<\/code><\/td><td class=\"has-text-align-left\" data-align=\"left\">Raised when the <code>input()<\/code> function hits the end-of-file condition.<\/td><\/tr><tr><td><code>FloatingPointError<\/code><\/td><td class=\"has-text-align-left\" data-align=\"left\">Raised when a floating-point operation fails.<\/td><\/tr><tr><td><code>GeneratorExit<\/code><\/td><td class=\"has-text-align-left\" data-align=\"left\">Raise when a generator&#8217;s close() method is called.<\/td><\/tr><tr><td><code>ImportError<\/code><\/td><td class=\"has-text-align-left\" data-align=\"left\">Raised when the imported module is not found.<\/td><\/tr><tr><td><code>IndexError<\/code><\/td><td class=\"has-text-align-left\" data-align=\"left\">Raised when the index of a sequence is out of range.<\/td><\/tr><tr><td><code>KeyError<\/code><\/td><td class=\"has-text-align-left\" data-align=\"left\">Raised when a key is not found in a dictionary.<\/td><\/tr><tr><td><code>KeyboardInterrupt<\/code><\/td><td class=\"has-text-align-left\" data-align=\"left\">Raised when the user hits the interrupt key (Ctrl+C or Delete)<\/td><\/tr><tr><td><code>MemoryError<\/code><\/td><td class=\"has-text-align-left\" data-align=\"left\">Raised when an operation runs out of memory.<\/td><\/tr><tr><td><code>NameError<\/code><\/td><td class=\"has-text-align-left\" data-align=\"left\">Raised when a variable is not found in the local or global scope.<\/td><\/tr><tr><td><code>OSError<\/code><\/td><td class=\"has-text-align-left\" data-align=\"left\">Raised when system operation causes system related error.<\/td><\/tr><tr><td><code>ReferenceError<\/code><\/td><td class=\"has-text-align-left\" data-align=\"left\">Raised when a weak reference proxy is used to access a garbage collected referent.<\/td><\/tr><\/tbody><\/table><figcaption>Python Built-in Exceptions<\/figcaption><\/figure>\n\n\n\n<p><strong>Example<\/strong>: The <code>FilenotfoundError<\/code> is raised when a file in not present on the disk<\/p>\n\n\n<div class=\"hljstoolbar\"><pre id=\"code3\"  class=\"wp-block-code language-python\" aria-describedby=\"shcb-language-5\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">fp = open(<span class=\"hljs-string\">\"test.txt\"<\/span>, <span class=\"hljs-string\">\"r\"<\/span>)\n<span class=\"hljs-keyword\">if<\/span> fp:\n    print(<span class=\"hljs-string\">\"file is opened successfully\"<\/span>)\n<\/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><button class=\"hljs-copy-button\" onclick=\"copy_code('code3', this);\"><i class=\"far fa-copy1\" aria-hidden=\"true\"><\/i><\/button><button class=\"hljs-run-button\" onclick=\"run_code('code3');\"><i class=\"far fa-play-circle\" aria-hidden=\"true\"><\/i> Run<\/button><\/div>\n\n\n<p><strong>Output<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">FileNotFoundError: [Errno 2] No such file or directory: 'test.txt'<\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-the-try-and-except-block-to-handling-exceptions\">The <code>try<\/code> and <code>except<\/code> Block to Handling Exceptions<\/h2>\n\n\n\n<p>When an exception occurs, Python stops the program execution and generates an exception message. It is highly recommended to handle exceptions. The doubtful code that may raise an exception is called risky code.<\/p>\n\n\n\n<p>To handle exceptions we need to use try and except block. Define risky code that can raise an exception inside the <code>try<\/code> block and corresponding handling code inside the <code>except<\/code> block.<\/p>\n\n\n\n<p><strong>Syntax<\/strong><\/p>\n\n\n<pre id=\"syntax\" class=\"wp-block-code language-python\" aria-describedby=\"shcb-language-6\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-keyword\">try<\/span> :\n    <span class=\"hljs-comment\"># statements in try block<\/span>\n<span class=\"hljs-keyword\">except<\/span> :\n    <span class=\"hljs-comment\"># executed when exception occured in try block<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-6\"><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<div class=\"wp-block-image is-style-default\"><figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"352\" height=\"262\" src=\"https:\/\/pynative.com\/wp-content\/uploads\/2021\/03\/try-except.png\" alt=\"try-except block\" class=\"wp-image-9214\" srcset=\"https:\/\/pynative.com\/wp-content\/uploads\/2021\/03\/try-except.png 352w, https:\/\/pynative.com\/wp-content\/uploads\/2021\/03\/try-except-300x223.png 300w\" sizes=\"auto, (max-width: 352px) 100vw, 352px\" \/><figcaption>try-except block<\/figcaption><\/figure><\/div>\n\n\n\n<p>The try block is for risky code that can raise an exception and the except block to handle error raised in a try block. For example, if we divide any number by zero, try block will throw <code>ZeroDivisionError<\/code>, so we should handle that exception in the except block.<\/p>\n\n\n\n<p>When we do not use <code>try\u2026except<\/code> block in the program, the program terminates abnormally, or it will be nongraceful termination of the program.<\/p>\n\n\n\n<p>Now let&#8217;s see the example when we do not use <code>try\u2026except<\/code> block for handling exceptions.<\/p>\n\n\n\n<p><strong>Example:<\/strong><\/p>\n\n\n<div class=\"hljstoolbar\"><pre id=\"code4\"  class=\"wp-block-code language-python\" aria-describedby=\"shcb-language-7\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">a = <span class=\"hljs-number\">10<\/span>\nb = <span class=\"hljs-number\">0<\/span>\nc = a \/ b\nprint(<span class=\"hljs-string\">\"a\/b = %d\"<\/span> % c)<\/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><button class=\"hljs-copy-button\" onclick=\"copy_code('code4', this);\"><i class=\"far fa-copy1\" aria-hidden=\"true\"><\/i><\/button><button class=\"hljs-run-button\" onclick=\"run_code('code4');\"><i class=\"far fa-play-circle\" aria-hidden=\"true\"><\/i> Run<\/button><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-8\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">Traceback (most recent call last):\n  File <span class=\"hljs-string\">\"E:\/demos\/exception.py\"<\/span>, line <span class=\"hljs-number\">3<\/span>, <span class=\"hljs-keyword\">in<\/span> &lt;module&gt;\n    c = a \/ b\nZeroDivisionError: division by zero<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-8\"><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>We can see in the above code when we are divided by 0; Python throws an exception as <code>ZeroDivisionError<\/code> and the program terminated <strong>abnormally<\/strong>.<\/p>\n\n\n\n<p>We can handle the above exception using the <code>try\u2026except<\/code> block. See the following code.<\/p>\n\n\n\n<p><strong>Example<\/strong><\/p>\n\n\n<div class=\"hljstoolbar\"><pre id=\"code5\"  class=\"wp-block-code language-python\" aria-describedby=\"shcb-language-9\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-keyword\">try<\/span>:\n    a = <span class=\"hljs-number\">10<\/span>\n    b = <span class=\"hljs-number\">0<\/span>\n    c = a\/b\n    print(<span class=\"hljs-string\">\"The answer of a divide by b:\"<\/span>, c)\n<span class=\"hljs-keyword\">except<\/span>:\n    print(<span class=\"hljs-string\">\"Can't divide with zero. Provide different number\"<\/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><button class=\"hljs-copy-button\" onclick=\"copy_code('code5', this);\"><i class=\"far fa-copy1\" aria-hidden=\"true\"><\/i><\/button><button class=\"hljs-run-button\" onclick=\"run_code('code5');\"><i class=\"far fa-play-circle\" aria-hidden=\"true\"><\/i> Run<\/button><\/div>\n\n\n<p>Output<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">Can't divide with zero. Provide different number<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-catching-specific-exceptions\">Catching Specific Exceptions <\/h3>\n\n\n\n<p>We can also catch a specific exception. In the above example, we did not mention any specific exception in the except block. Catch all the exceptions and handle every exception is not good programming practice. <\/p>\n\n\n\n<p>It is good practice to<strong> specify an exact exception that the except clause should catch<\/strong>. For example, to catch an exception that occurs when the user enters a non-numerical value instead of a number, we can catch only the built-in ValueError exception that will handle such an event properly.<\/p>\n\n\n\n<p>We can specify which exception <code>except<\/code> block should catch or handle. A <code>try<\/code> block can be followed by multiple numbers of <code>except<\/code> blocks to handle the different exceptions. But only one exception will be executed when an exception occurs.<\/p>\n\n\n\n<p><strong>Example<\/strong><\/p>\n\n\n\n<p>In this example, we will ask the user for the denominator value. If the user enters a number, the program will evaluate and produce the result.<\/p>\n\n\n\n<p>If the user enters a non-numeric value then, the try block will throw a <code>ValueError<\/code> exception, and we can catch that using a first catch block &#8216;except ValueError&#8217; by printing the message &#8216;Entered value is wrong&#8217;.<\/p>\n\n\n\n<p>And suppose the user enters the denominator as zero. In that case, the try block will throw a <code>ZeroDivisionError<\/code>, and we can catch that using a second catch block by printing the message &#8216;Can&#8217;t divide by zero&#8217;.<\/p>\n\n\n<div class=\"hljstoolbar\"><pre id=\"code6\"  class=\"wp-block-code language-python\" aria-describedby=\"shcb-language-10\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-keyword\">try<\/span>:\n    a = int(input(<span class=\"hljs-string\">\"Enter value of a:\"<\/span>))\n    b = int(input(<span class=\"hljs-string\">\"Enter value of b:\"<\/span>))\n    c = a\/b\n    print(<span class=\"hljs-string\">\"The answer of a divide by b:\"<\/span>, c)\n<span class=\"hljs-keyword\">except<\/span> ValueError:\n    print(<span class=\"hljs-string\">\"Entered value is wrong\"<\/span>)\n<span class=\"hljs-keyword\">except<\/span> ZeroDivisionError:\n    print(<span class=\"hljs-string\">\"Can't divide by zero\"<\/span>)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-10\"><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><button class=\"hljs-copy-button\" onclick=\"copy_code('code6', this);\"><i class=\"far fa-copy1\" aria-hidden=\"true\"><\/i><\/button><button class=\"hljs-run-button\" onclick=\"run_code('code6');\"><i class=\"far fa-play-circle\" aria-hidden=\"true\"><\/i> Run<\/button><\/div>\n\n\n<div class=\"wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex\">\n<div class=\"wp-block-column is-layout-flow wp-block-column-is-layout-flow\">\n<p><strong>Output 1<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">Enter value of a:Ten\nEntered value is wrong<\/pre>\n<\/div>\n\n\n\n<div class=\"wp-block-column is-layout-flow wp-block-column-is-layout-flow\">\n<p><strong>Output 2<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">Enter value of a:10\nEnter value of b:0\nCan't divide by zero<\/pre>\n<\/div>\n<\/div>\n\n\n\n<p><strong>Output <\/strong>3:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">Enter value of a:10\nEnter value of b:2\nThe answer of a divide by b: 5.0<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-handle-multiple-exceptions-with-a-single-except-clause\">Handle multiple exceptions with a single except clause<\/h3>\n\n\n\n<p>We can also handle multiple exceptions with a single <code>except<\/code> clause. For that, we can use an <code>tuple<\/code> of values to specify multiple exceptions in an <code>except<\/code> clause.<\/p>\n\n\n\n<p><strong>Example<\/strong><\/p>\n\n\n\n<p>Let&#8217;s see how to specifiy two exceptions in the single except clause.<\/p>\n\n\n<div class=\"hljstoolbar\"><pre id=\"code7\"  class=\"wp-block-code language-python\" aria-describedby=\"shcb-language-11\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-keyword\">try<\/span>:\n    a = int(input(<span class=\"hljs-string\">\"Enter value of a:\"<\/span>))\n    b = int(input(<span class=\"hljs-string\">\"Enter value of b:\"<\/span>))\n    c = a \/ b\n    print(<span class=\"hljs-string\">\"The answer of a divide by b:\"<\/span>, c)\n<span class=\"hljs-keyword\">except<\/span>(ValueError, ZeroDivisionError):\n    print(<span class=\"hljs-string\">\"Please enter a valid value\"<\/span>)<\/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><button class=\"hljs-copy-button\" onclick=\"copy_code('code7', this);\"><i class=\"far fa-copy1\" aria-hidden=\"true\"><\/i><\/button><button class=\"hljs-run-button\" onclick=\"run_code('code7');\"><i class=\"far fa-play-circle\" aria-hidden=\"true\"><\/i> Run<\/button><\/div>\n\n\n<h2 class=\"wp-block-heading\" id=\"h-using-try-with-finally\">Using <code>try<\/code> with <code>finally<\/code><\/h2>\n\n\n\n<p>Python provides the <code>finally<\/code> block, which is used with the try block statement. <strong>The <code>finally<\/code> block is used to write a block of code that must execute, whether the <code>try<\/code> block raises an error or not<\/strong>.<\/p>\n\n\n\n<p>Mainly, the <code>finally<\/code> block is used to release the external resource. This block provides a guarantee of execution.<\/p>\n\n\n\n<div class=\"wp-block-image is-style-default\"><figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"865\" height=\"470\" src=\"https:\/\/pynative.com\/wp-content\/uploads\/2021\/03\/try_except_finally.png\" alt=\"try-except-finally block\" class=\"wp-image-9213\" srcset=\"https:\/\/pynative.com\/wp-content\/uploads\/2021\/03\/try_except_finally.png 865w, https:\/\/pynative.com\/wp-content\/uploads\/2021\/03\/try_except_finally-300x163.png 300w, https:\/\/pynative.com\/wp-content\/uploads\/2021\/03\/try_except_finally-768x417.png 768w\" sizes=\"auto, (max-width: 865px) 100vw, 865px\" \/><figcaption>try-except-finally block<\/figcaption><\/figure><\/div>\n\n\n\n<p><strong>Clean-up actions using <code>finally<\/code><\/strong><\/p>\n\n\n\n<p>Sometimes we want to execute some action at any cost, even if an error occurred in a program. In Python, we can perform such actions using a finally statement with a try and except statement.<\/p>\n\n\n\n<p>The block of code written in the finally block will always execute even there is an exception in the try and except block.<\/p>\n\n\n\n<p>If an exception is not handled by except clause, then finally block executes first, then the exception is thrown. This process is known as clean-up action.<\/p>\n\n\n\n<p><strong>Syntax<\/strong><\/p>\n\n\n<pre id=\"syntax\" class=\"wp-block-code language-python\" aria-describedby=\"shcb-language-12\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-keyword\">try<\/span>:    \n    <span class=\"hljs-comment\"># block of code     <\/span>\n    <span class=\"hljs-comment\"># this may throw an exception    <\/span>\n<span class=\"hljs-keyword\">finally<\/span>:    \n    <span class=\"hljs-comment\"># block of code    <\/span>\n    <span class=\"hljs-comment\"># this will always be executed <\/span>\n    <span class=\"hljs-comment\"># after the try and any except block   <\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-12\"><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><strong>Example<\/strong><\/p>\n\n\n<div class=\"hljstoolbar\"><pre id=\"code8\"  class=\"wp-block-code language-python\" aria-describedby=\"shcb-language-13\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-keyword\">try<\/span>:\n    a = int(input(<span class=\"hljs-string\">\"Enter value of a:\"<\/span>))\n    b = int(input(<span class=\"hljs-string\">\"Enter value of b:\"<\/span>))\n    c = a \/ b\n    print(<span class=\"hljs-string\">\"The answer of a divide by b:\"<\/span>, c)\n\n<span class=\"hljs-keyword\">except<\/span> ZeroDivisionError:\n    print(<span class=\"hljs-string\">\"Can't divide with zero\"<\/span>)\n<span class=\"hljs-keyword\">finally<\/span>:\n    print(<span class=\"hljs-string\">\"Inside a finally block\"<\/span>)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-13\"><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><button class=\"hljs-copy-button\" onclick=\"copy_code('code8', this);\"><i class=\"far fa-copy1\" aria-hidden=\"true\"><\/i><\/button><button class=\"hljs-run-button\" onclick=\"run_code('code8');\"><i class=\"far fa-play-circle\" aria-hidden=\"true\"><\/i> Run<\/button><\/div>\n\n\n<div class=\"wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex\">\n<div class=\"wp-block-column is-layout-flow wp-block-column-is-layout-flow\">\n<p><strong>Output 1<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">Enter value of a:20\nEnter value of b:5\nThe answer of a divide by b: 4.0\nInside a finally block<\/pre>\n<\/div>\n\n\n\n<div class=\"wp-block-column is-layout-flow wp-block-column-is-layout-flow\">\n<p><strong>Output 2<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">Enter value of a:20\nEnter value of b:0\nCan't divide with zero\nInside a finally block<\/pre>\n<\/div>\n<\/div>\n\n\n\n<p>In the above example, we can see we divide a number by 0 and get an error, and the program <strong>terminates normally<\/strong>. In this case, the <code>finally<\/code> block was also executed.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-using-try-with-else-clause\">Using <code>try<\/code> with <code>else<\/code> clause<\/h2>\n\n\n\n<p>Sometimes we might want to run a specific block of code. In that case, we can use <code>else<\/code> block with the <code>try-except<\/code> block. The <code>else<\/code> block will be executed if and only if there are no exception is the <code>try<\/code> block. For these cases, we can use the optional <code>else<\/code> statement with the <code>try<\/code> statement.<\/p>\n\n\n\n<p><strong>Why to use <code>else<\/code> block with try?<\/strong><\/p>\n\n\n\n<p>Use else statemen with try block to check if try block executed without any exception or if you want to run a specific code only if an exception is not raised<\/p>\n\n\n\n<div class=\"wp-block-image is-style-default\"><figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"869\" height=\"476\" src=\"https:\/\/pynative.com\/wp-content\/uploads\/2021\/03\/try_else.png\" alt=\"try-else block\" class=\"wp-image-9212\" srcset=\"https:\/\/pynative.com\/wp-content\/uploads\/2021\/03\/try_else.png 869w, https:\/\/pynative.com\/wp-content\/uploads\/2021\/03\/try_else-300x164.png 300w, https:\/\/pynative.com\/wp-content\/uploads\/2021\/03\/try_else-768x421.png 768w\" sizes=\"auto, (max-width: 869px) 100vw, 869px\" \/><\/figure><\/div>\n\n\n\n<p><strong>Syntax<\/strong><\/p>\n\n\n<pre id=\"syntax\" class=\"wp-block-code language-python\" aria-describedby=\"shcb-language-14\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-keyword\">try<\/span>:    \n    <span class=\"hljs-comment\"># block of code     <\/span>\n<span class=\"hljs-keyword\">except<\/span> Exception1:    \n    <span class=\"hljs-comment\"># block of code     <\/span>\n<span class=\"hljs-keyword\">else<\/span>:    \n    <span class=\"hljs-comment\"># this code executes when exceptions not occured    <\/span><\/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<ul class=\"wp-block-list\" id=\"block-ff7f9c60-c716-458e-bb7e-b4c24236c485\"><li><strong><code>try<\/code>:<\/strong> The <code>try<\/code> block for risky code that can throw an exception.<\/li><li><code><strong>except<\/strong><\/code>: The <code>except<\/code> block to handle error raised in a <code>try<\/code> block.<\/li><li><code><strong>else<\/strong><\/code>: The <code>else<\/code> block is executed if there is no exception.<\/li><\/ul>\n\n\n\n<p><strong>Example<\/strong><\/p>\n\n\n<div class=\"hljstoolbar\"><pre id=\"code9\"  class=\"wp-block-code language-python\" aria-describedby=\"shcb-language-15\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-keyword\">try<\/span>:\n    a = int(input(<span class=\"hljs-string\">\"Enter value of a:\"<\/span>))\n    b = int(input(<span class=\"hljs-string\">\"Enter value of b:\"<\/span>))\n    c = a \/ b\n    print(<span class=\"hljs-string\">\"a\/b = %d\"<\/span> % c)\n\n<span class=\"hljs-keyword\">except<\/span> ZeroDivisionError:\n    print(<span class=\"hljs-string\">\"Can't divide by zero\"<\/span>)\n<span class=\"hljs-keyword\">else<\/span>:\n    print(<span class=\"hljs-string\">\"We are in else block \"<\/span>)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-15\"><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><button class=\"hljs-copy-button\" onclick=\"copy_code('code9', this);\"><i class=\"far fa-copy1\" aria-hidden=\"true\"><\/i><\/button><button class=\"hljs-run-button\" onclick=\"run_code('code9');\"><i class=\"far fa-play-circle\" aria-hidden=\"true\"><\/i> Run<\/button><\/div>\n\n\n<div class=\"wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex\">\n<div class=\"wp-block-column is-layout-flow wp-block-column-is-layout-flow\">\n<p><strong>Output 1<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">Enter value of a: 20\nEnter value of b:4\na\/b = 5\nWe are in else block <\/pre>\n<\/div>\n\n\n\n<div class=\"wp-block-column is-layout-flow wp-block-column-is-layout-flow\">\n<p><strong>Output 2<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">Enter value of a: 20\nEnter value of b:0\nCan't divide by zero<\/pre>\n<\/div>\n<\/div>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-raising-an-exceptions\">Raising an Exceptions<\/h2>\n\n\n\n<p>In Python, the <code>raise<\/code> statement allows us to throw an exception. The single arguments in the <code>raise<\/code> statement show an exception to be raised. This can be either an exception object or an <code>Exception<\/code> class that is derived from the <code>Exception<\/code> class. <\/p>\n\n\n\n<p>The <code>raise<\/code> statement is useful in situations where we need to raise an exception to the caller program. We can raise exceptions in cases such as wrong data received or any validation failure.<\/p>\n\n\n\n<p>Follow the below steps to raise an exception:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Create an exception of the appropriate type. Use the existing built-in exceptions or create your won exception as per the requirement.<\/li><li>Pass the appropriate data while raising an exception.<\/li><li>Execute a raise statement, by providing the exception class.<\/li><\/ul>\n\n\n\n<p>The syntax to use the <code>raise<\/code> statement is given below.<\/p>\n\n\n<pre id=\"syntax\" class=\"wp-block-code language-python\" aria-describedby=\"shcb-language-16\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-keyword\">raise<\/span> Exception_class,&lt;value&gt;  <\/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><strong>Example<\/strong><\/p>\n\n\n\n<p>In this example, we will throw an exception if interest rate is greater than 100.<\/p>\n\n\n<div class=\"hljstoolbar\"><pre id=\"code10\"  class=\"wp-block-code language-python\" aria-describedby=\"shcb-language-17\" 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\">simple_interest<\/span><span class=\"hljs-params\">(amount, year, rate)<\/span>:<\/span>\n    <span class=\"hljs-keyword\">try<\/span>:\n        <span class=\"hljs-keyword\">if<\/span> rate &gt; <span class=\"hljs-number\">100<\/span>:\n            <span class=\"hljs-keyword\">raise<\/span> ValueError(rate)\n        interest = (amount * year * rate) \/ <span class=\"hljs-number\">100<\/span>\n        print(<span class=\"hljs-string\">'The Simple Interest is'<\/span>, interest)\n        <span class=\"hljs-keyword\">return<\/span> interest\n    <span class=\"hljs-keyword\">except<\/span> ValueError:\n        print(<span class=\"hljs-string\">'interest rate is out of range'<\/span>, rate)\n\nprint(<span class=\"hljs-string\">'Case 1'<\/span>)\nsimple_interest(<span class=\"hljs-number\">800<\/span>, <span class=\"hljs-number\">6<\/span>, <span class=\"hljs-number\">8<\/span>)\n\nprint(<span class=\"hljs-string\">'Case 2'<\/span>)\nsimple_interest(<span class=\"hljs-number\">800<\/span>, <span class=\"hljs-number\">6<\/span>, <span class=\"hljs-number\">800<\/span>)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-17\"><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><button class=\"hljs-copy-button\" onclick=\"copy_code('code10', this);\"><i class=\"far fa-copy1\" aria-hidden=\"true\"><\/i><\/button><button class=\"hljs-run-button\" onclick=\"run_code('code10');\"><i class=\"far fa-play-circle\" aria-hidden=\"true\"><\/i> Run<\/button><\/div>\n\n\n<p><strong>Output<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">Case 1\nThe Simple Interest is 384.0\n\nCase 2\ninterest rate is out of range 800<\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-exception-chaining\">Exception Chaining<\/h2>\n\n\n\n<p>The exception chaining is available only in Python 3. The <code>raise<\/code> statements allow us as optional <code>from<\/code> statement, which enables chaining exceptions. So we can implement exception chaining in python3 by using <code>raise\u2026from<\/code> clause to <strong>chain exception<\/strong>.<\/p>\n\n\n\n<p>When exception raise, exception chaining happens automatically. The exception can be raised inside <code>except<\/code> or <code>finally<\/code> block section. We also disabled exception chaining by using <code>from None<\/code> idiom.<\/p>\n\n\n\n<p><strong>Example<\/strong><\/p>\n\n\n<div class=\"hljstoolbar\"><pre id=\"code11\"  class=\"wp-block-code language-python\" aria-describedby=\"shcb-language-18\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-keyword\">try<\/span>:\n    a = int(input(<span class=\"hljs-string\">\"Enter value of a:\"<\/span>))\n    b = int(input(<span class=\"hljs-string\">\"Enter value of b:\"<\/span>))\n    c = a\/b\n    print(<span class=\"hljs-string\">\"The answer of a divide by b:\"<\/span>, c)\n<span class=\"hljs-keyword\">except<\/span> ZeroDivisionError <span class=\"hljs-keyword\">as<\/span> e:\n    <span class=\"hljs-keyword\">raise<\/span> ValueError(<span class=\"hljs-string\">\"Division failed\"<\/span>) <span class=\"hljs-keyword\">from<\/span> e\n\n<span class=\"hljs-comment\"># Output: Enter value of a:10<\/span>\n<span class=\"hljs-comment\"># Enter value of b:0<\/span>\n<span class=\"hljs-comment\"># ValueError: Division failed<\/span><\/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><button class=\"hljs-copy-button\" onclick=\"copy_code('code11', this);\"><i class=\"far fa-copy1\" aria-hidden=\"true\"><\/i><\/button><button class=\"hljs-run-button\" onclick=\"run_code('code11');\"><i class=\"far fa-play-circle\" aria-hidden=\"true\"><\/i> Run<\/button><\/div>\n\n\n<p>In the above example, we use exception chaining using <code>raise...from<\/code> clause and raise <code>ValueError<\/code> division failed.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-custom-and-user-defined-exceptions\">Custom and User-defined Exceptions<\/h2>\n\n\n\n<p>Sometimes we have to define and <code>raise<\/code> exceptions explicitly to indicate that something goes wrong. Such a type of exception is called a <strong>user-defined exception <\/strong>or<strong> customized exception.<\/strong><\/p>\n\n\n\n<p>The user can define custom exceptions by creating a new class. This new exception class has to derive either directly or indirectly from the built-in class <code>Exception<\/code>. In Python, most of the built-in exceptions also derived from the <code>Exception<\/code> class.<\/p>\n\n\n<div class=\"hljstoolbar\"><pre id=\"code12\"  class=\"wp-block-code language-python\" aria-describedby=\"shcb-language-19\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Error<\/span><span class=\"hljs-params\">(Exception)<\/span>:<\/span>\n    <span class=\"hljs-string\">\"\"\"Base class for other exceptions\"\"\"<\/span>\n    <span class=\"hljs-keyword\">pass<\/span>\n\n<span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">ValueTooSmallError<\/span><span class=\"hljs-params\">(Error)<\/span>:<\/span>\n    <span class=\"hljs-string\">\"\"\"Raised when the input value is small\"\"\"<\/span>\n    <span class=\"hljs-keyword\">pass<\/span>\n\n<span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">ValueTooLargeError<\/span><span class=\"hljs-params\">(Error)<\/span>:<\/span>\n    <span class=\"hljs-string\">\"\"\"Raised when the input value is large\"\"\"<\/span>\n    <span class=\"hljs-keyword\">pass<\/span>\n\n<span class=\"hljs-keyword\">while<\/span>(<span class=\"hljs-literal\">True<\/span>):\n    <span class=\"hljs-keyword\">try<\/span>:\n        num = int(input(<span class=\"hljs-string\">\"Enter any value in 10 to 50 range: \"<\/span>))\n        <span class=\"hljs-keyword\">if<\/span> num &lt; <span class=\"hljs-number\">10<\/span>:\n            <span class=\"hljs-keyword\">raise<\/span> ValueTooSmallError\n        <span class=\"hljs-keyword\">elif<\/span> num &gt; <span class=\"hljs-number\">50<\/span>:\n            <span class=\"hljs-keyword\">raise<\/span> ValueTooLargeError\n        <span class=\"hljs-keyword\">break<\/span>\n    <span class=\"hljs-keyword\">except<\/span> ValueTooSmallError:\n            print(<span class=\"hljs-string\">\"Value is below range..try again\"<\/span>)\n\n    <span class=\"hljs-keyword\">except<\/span> ValueTooLargeError:\n            print(<span class=\"hljs-string\">\"value out of range...try again\"<\/span>)\n\nprint(<span class=\"hljs-string\">\"Great! value in correct range.\"<\/span>)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-19\"><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><button class=\"hljs-copy-button\" onclick=\"copy_code('code12', this);\"><i class=\"far fa-copy1\" aria-hidden=\"true\"><\/i><\/button><button class=\"hljs-run-button\" onclick=\"run_code('code12');\"><i class=\"far fa-play-circle\" aria-hidden=\"true\"><\/i> Run<\/button><\/div>\n\n\n<p><strong>Output<\/strong><\/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\">Enter any value <span class=\"hljs-keyword\">in<\/span> <span class=\"hljs-number\">10<\/span> to <span class=\"hljs-number\">50<\/span> range: <span class=\"hljs-number\">5<\/span>\nValue <span class=\"hljs-keyword\">is<\/span> below range..<span class=\"hljs-keyword\">try<\/span> again\n\nEnter any value <span class=\"hljs-keyword\">in<\/span> <span class=\"hljs-number\">10<\/span> to <span class=\"hljs-number\">50<\/span> range: <span class=\"hljs-number\">60<\/span>\nvalue out of range...<span class=\"hljs-keyword\">try<\/span> again\n\nEnter any value <span class=\"hljs-keyword\">in<\/span> <span class=\"hljs-number\">10<\/span> to <span class=\"hljs-number\">50<\/span> range: <span class=\"hljs-number\">11<\/span>\nGreat! value <span class=\"hljs-keyword\">in<\/span> correct range.<\/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>In the above example, we create two custom classes or user-defined classes with names, <code>ValueTooSmallError<\/code> and <code>ValueTooLargeError<\/code>.When the entered value is below the range, it will raise V<code>alueTooSmallError<\/code> and if the value is out of then, it will <code>raise<\/code> <code>ValueTooLargeError<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-customizing-exception-classes\">Customizing Exception Classes<\/h3>\n\n\n\n<p>We can customize the classes by accepting arguments as per our requirements. Any custom exception class must be Extending from <code>BaseException<\/code> class or subclass of <code>BaseException<\/code>.<\/p>\n\n\n\n<p>In the above example, we create a custom class that is inherited from the base class <code>Exception<\/code>. This class takes one argument age. When entered age is negative, it will raise <code>NegativeAgeError<\/code>.<\/p>\n\n\n<div class=\"hljstoolbar\"><pre id=\"code13\"  class=\"wp-block-code language-python\" aria-describedby=\"shcb-language-21\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">NegativeAgeError<\/span><span class=\"hljs-params\">(Exception)<\/span>:<\/span>\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__init__<\/span><span class=\"hljs-params\">(self, age, )<\/span>:<\/span>\n        message = <span class=\"hljs-string\">\"Age should not be negative\"<\/span>\n        self.age = age\n        self.message = message\n\nage = int(input(<span class=\"hljs-string\">\"Enter age: \"<\/span>))\n<span class=\"hljs-keyword\">if<\/span> age &lt; <span class=\"hljs-number\">0<\/span>:\n    <span class=\"hljs-keyword\">raise<\/span> NegativeAgeError(age)\n<span class=\"hljs-comment\"># Output:<\/span>\n<span class=\"hljs-comment\"># raise NegativeAgeError(age)<\/span>\n<span class=\"hljs-comment\"># __main__.NegativeAgeError: -9<\/span>\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-21\"><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><button class=\"hljs-copy-button\" onclick=\"copy_code('code13', this);\"><i class=\"far fa-copy1\" aria-hidden=\"true\"><\/i><\/button><button class=\"hljs-run-button\" onclick=\"run_code('code13');\"><i class=\"far fa-play-circle\" aria-hidden=\"true\"><\/i> Run<\/button><\/div>\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">Enter age: -28\n Traceback (most recent call last):\n   File \"E:\/demos\/exception.py\", line 11, in \n     raise NegativeAgeError(age)\n <strong>main<\/strong>.NegativeAgeError: -28<\/pre>\n\n\n\n<p><strong>Done<\/strong><\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-exception-lifecycle\">Exception Lifecycle<\/h2>\n\n\n\n<ul class=\"wp-block-list\"><li>When an exception is raised, The runtime system attempts to find a handler for the exception by backtracking the ordered list of methods calls. This is known as the&nbsp;<em>call stack<\/em>.<\/li><li>If a handler is found (i.e., if <code>except<\/code> block is located), there are two cases in the <code>except<\/code> block; either exception is handled or possibly re-thrown.<\/li><li>If the handler is not found (the runtime backtracks to the method chain&#8217;s last calling method), the exception stack trace is printed to the standard error console, and the application stops its execution.<\/li><\/ul>\n\n\n\n<p><strong>Example<\/strong><\/p>\n\n\n<div class=\"hljstoolbar\"><pre id=\"code14\"  class=\"wp-block-code language-python\" aria-describedby=\"shcb-language-22\" 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\">sum_of_list<\/span><span class=\"hljs-params\">(numbers)<\/span>:<\/span>\n    <span class=\"hljs-keyword\">return<\/span> sum(numbers)\n\n<span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">average<\/span><span class=\"hljs-params\">(sum, n)<\/span>:<\/span>\n    <span class=\"hljs-comment\"># ZeroDivisionError if list is empty<\/span>\n    <span class=\"hljs-keyword\">return<\/span> sum \/ n\n\n<span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">final_data<\/span><span class=\"hljs-params\">(data)<\/span>:<\/span>\n    <span class=\"hljs-keyword\">for<\/span> item <span class=\"hljs-keyword\">in<\/span> data:\n        print(<span class=\"hljs-string\">\"Average:\"<\/span>, average(sum_of_list(item), len(item)))\n\nlist1 = &#91;<span class=\"hljs-number\">10<\/span>, <span class=\"hljs-number\">20<\/span>, <span class=\"hljs-number\">30<\/span>, <span class=\"hljs-number\">40<\/span>, <span class=\"hljs-number\">50<\/span>]\nlist2 = &#91;<span class=\"hljs-number\">100<\/span>, <span class=\"hljs-number\">200<\/span>, <span class=\"hljs-number\">300<\/span>, <span class=\"hljs-number\">400<\/span>, <span class=\"hljs-number\">500<\/span>]\n<span class=\"hljs-comment\"># empty list<\/span>\nlist3 = &#91;]\nlists = &#91;list1, list2, list3]\nfinal_data(lists)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-22\"><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><button class=\"hljs-copy-button\" onclick=\"copy_code('code14', this);\"><i class=\"far fa-copy1\" aria-hidden=\"true\"><\/i><\/button><button class=\"hljs-run-button\" onclick=\"run_code('code14');\"><i class=\"far fa-play-circle\" aria-hidden=\"true\"><\/i> Run<\/button><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">Average: 30.0\nTraceback (most recent call last):\nFile \"E:\/demos\/exceptions.py\", line 17, in\nfinal_data(lists)\nFile \"E:\/demos\/exceptions.py\", line 11, in final_data\nprint(\"Average:\", average(sum_of_list(item), len(item)))\nAverage: 300.0\nFile \"E:\/demos\/exceptions.py\", line 6, in average\nreturn sum \/ n\nZeroDivisionError: division by zero<\/pre>\n\n\n\n<p>The above stack trace shows the methods that are being called from main() until the method created an exception condition. It also shows line numbers.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-warnings\">Warnings<\/h2>\n\n\n\n<p>Several built-in exceptions represent warning categories. This categorization is helpful to be able to filter out groups of warnings.<\/p>\n\n\n\n<p>The warning doesn&#8217;t stop the execution of a program it indicates the possible improvement<\/p>\n\n\n\n<p>Below is the list of warning exception<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Waring Class<\/th><th>Meaning<\/th><\/tr><\/thead><tbody><tr><td>Warning<\/td><td>Base class for warning categories<\/td><\/tr><tr><td>UserWarning<\/td><td>Base class for warnings generated by user code<\/td><\/tr><tr><td>DeprecationWarning<\/td><td>Warnings about deprecated features<\/td><\/tr><tr><td>PendingDeprecationWarning<\/td><td>Warnings about features that are obsolete and expected to be deprecated in the future, but are not deprecated at the moment.<\/td><\/tr><tr><td>SyntaxWarning<\/td><td>Warnings about dubious syntax<\/td><\/tr><tr><td>RuntimeWarning<\/td><td>Warnings about the dubious runtime behavior<\/td><\/tr><tr><td>FutureWarning<\/td><td>Warnings about probable mistakes in module imports<\/td><\/tr><tr><td>ImportWarning<\/td><td>Warnings about probable mistakes in module imports<\/td><\/tr><tr><td>UnicodeWarning<\/td><td>Warnings related to Unicode data<\/td><\/tr><tr><td>BytesWarning<\/td><td>Warnings related to bytes and bytearray.<\/td><\/tr><tr><td>ResourceWarning<\/td><td>Warnings related to resource usage<\/td><\/tr><\/tbody><\/table><figcaption>Python Exception warnings<\/figcaption><\/figure>\n","protected":false},"excerpt":{"rendered":"<p>In this article, you will learn error and exception handling in Python. By the end of the article, you\u2019ll know: How to handle exceptions using the try, except, and finally statements How to create a custom exception How to raise an exceptions How to use built-in exception effectively to build robust Python programs What are [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":9211,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_genesis_hide_title":false,"_genesis_hide_breadcrumbs":false,"_genesis_hide_singular_image":false,"_genesis_hide_footer_widgets":false,"_genesis_custom_body_class":"","_genesis_custom_post_class":"","_genesis_layout":"","footnotes":""},"categories":[22,1],"tags":[32],"class_list":{"0":"post-9210","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-python","8":"category-basics","9":"tag-python-basics","10":"entry"},"yoast_head":"<!-- This site is optimized with the Yoast SEO Premium plugin v27.3 (Yoast SEO v27.3) - https:\/\/yoast.com\/product\/yoast-seo-premium-wordpress\/ -->\n<title>Python Exceptions and Errors &#8211; PYnative<\/title>\n<meta name=\"description\" content=\"Learn Python Exceptions and Errors in depth. handling exception with try-except-finally block. Raise exceptions and create custom exceptions\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/pynative.com\/python-exceptions\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Python Exceptions and Errors\" \/>\n<meta property=\"og:description\" content=\"Learn Python Exceptions and Errors in depth. handling exception with try-except-finally block. Raise exceptions and create custom exceptions\" \/>\n<meta property=\"og:url\" content=\"https:\/\/pynative.com\/python-exceptions\/\" \/>\n<meta property=\"og:site_name\" content=\"PYnative\" \/>\n<meta property=\"article:published_time\" content=\"2021-03-24T08:41:10+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2021-03-25T02:56:43+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/pynative.com\/wp-content\/uploads\/2021\/03\/python_exception_handling.png\" \/>\n\t<meta property=\"og:image:width\" content=\"845\" \/>\n\t<meta property=\"og:image:height\" content=\"446\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Vishal\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@PyNative\" \/>\n<meta name=\"twitter:site\" content=\"@PyNative\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Vishal\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"15 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/pynative.com\\\/python-exceptions\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/pynative.com\\\/python-exceptions\\\/\"},\"author\":{\"name\":\"Vishal\",\"@id\":\"https:\\\/\\\/pynative.com\\\/#\\\/schema\\\/person\\\/64b55d5bde2265918c5a9931de4de71f\"},\"headline\":\"Python Exceptions and Errors\",\"datePublished\":\"2021-03-24T08:41:10+00:00\",\"dateModified\":\"2021-03-25T02:56:43+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/pynative.com\\\/python-exceptions\\\/\"},\"wordCount\":2179,\"commentCount\":2,\"publisher\":{\"@id\":\"https:\\\/\\\/pynative.com\\\/#\\\/schema\\\/person\\\/64b55d5bde2265918c5a9931de4de71f\"},\"image\":{\"@id\":\"https:\\\/\\\/pynative.com\\\/python-exceptions\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/pynative.com\\\/wp-content\\\/uploads\\\/2021\\\/03\\\/python_exception_handling.png\",\"keywords\":[\"Python Basics\"],\"articleSection\":[\"Python\",\"Python Basics\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\\\/\\\/pynative.com\\\/python-exceptions\\\/#respond\"]}],\"accessibilityFeature\":[\"tableOfContents\"]},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/pynative.com\\\/python-exceptions\\\/\",\"url\":\"https:\\\/\\\/pynative.com\\\/python-exceptions\\\/\",\"name\":\"Python Exceptions and Errors &#8211; PYnative\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/pynative.com\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/pynative.com\\\/python-exceptions\\\/#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/pynative.com\\\/python-exceptions\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/pynative.com\\\/wp-content\\\/uploads\\\/2021\\\/03\\\/python_exception_handling.png\",\"datePublished\":\"2021-03-24T08:41:10+00:00\",\"dateModified\":\"2021-03-25T02:56:43+00:00\",\"description\":\"Learn Python Exceptions and Errors in depth. handling exception with try-except-finally block. Raise exceptions and create custom exceptions\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/pynative.com\\\/python-exceptions\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/pynative.com\\\/python-exceptions\\\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/pynative.com\\\/python-exceptions\\\/#primaryimage\",\"url\":\"https:\\\/\\\/pynative.com\\\/wp-content\\\/uploads\\\/2021\\\/03\\\/python_exception_handling.png\",\"contentUrl\":\"https:\\\/\\\/pynative.com\\\/wp-content\\\/uploads\\\/2021\\\/03\\\/python_exception_handling.png\",\"width\":845,\"height\":446,\"caption\":\"Python Exceptions\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/pynative.com\\\/python-exceptions\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/pynative.com\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Python\",\"item\":\"https:\\\/\\\/pynative.com\\\/python\\\/\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"Python Exceptions and Errors\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/pynative.com\\\/#website\",\"url\":\"https:\\\/\\\/pynative.com\\\/\",\"name\":\"PYnative\",\"description\":\"Python Programming\",\"publisher\":{\"@id\":\"https:\\\/\\\/pynative.com\\\/#\\\/schema\\\/person\\\/64b55d5bde2265918c5a9931de4de71f\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/pynative.com\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":[\"Person\",\"Organization\"],\"@id\":\"https:\\\/\\\/pynative.com\\\/#\\\/schema\\\/person\\\/64b55d5bde2265918c5a9931de4de71f\",\"name\":\"Vishal\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/pynative.com\\\/wp-content\\\/uploads\\\/2019\\\/01\\\/vishalHule.jpg\",\"url\":\"https:\\\/\\\/pynative.com\\\/wp-content\\\/uploads\\\/2019\\\/01\\\/vishalHule.jpg\",\"contentUrl\":\"https:\\\/\\\/pynative.com\\\/wp-content\\\/uploads\\\/2019\\\/01\\\/vishalHule.jpg\",\"width\":968,\"height\":1065,\"caption\":\"Vishal\"},\"logo\":{\"@id\":\"https:\\\/\\\/pynative.com\\\/wp-content\\\/uploads\\\/2019\\\/01\\\/vishalHule.jpg\"},\"description\":\"Founder of PYnative.com. I am a Python developer and I love to write articles to help developers. | All the best for your future Python endeavors!\",\"sameAs\":[\"https:\\\/\\\/pynative.com\"]}]}<\/script>\n<!-- \/ Yoast SEO Premium plugin. -->","yoast_head_json":{"title":"Python Exceptions and Errors &#8211; PYnative","description":"Learn Python Exceptions and Errors in depth. handling exception with try-except-finally block. Raise exceptions and create custom exceptions","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/pynative.com\/python-exceptions\/","og_locale":"en_US","og_type":"article","og_title":"Python Exceptions and Errors","og_description":"Learn Python Exceptions and Errors in depth. handling exception with try-except-finally block. Raise exceptions and create custom exceptions","og_url":"https:\/\/pynative.com\/python-exceptions\/","og_site_name":"PYnative","article_published_time":"2021-03-24T08:41:10+00:00","article_modified_time":"2021-03-25T02:56:43+00:00","og_image":[{"width":845,"height":446,"url":"https:\/\/pynative.com\/wp-content\/uploads\/2021\/03\/python_exception_handling.png","type":"image\/png"}],"author":"Vishal","twitter_card":"summary_large_image","twitter_creator":"@PyNative","twitter_site":"@PyNative","twitter_misc":{"Written by":"Vishal","Est. reading time":"15 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/pynative.com\/python-exceptions\/#article","isPartOf":{"@id":"https:\/\/pynative.com\/python-exceptions\/"},"author":{"name":"Vishal","@id":"https:\/\/pynative.com\/#\/schema\/person\/64b55d5bde2265918c5a9931de4de71f"},"headline":"Python Exceptions and Errors","datePublished":"2021-03-24T08:41:10+00:00","dateModified":"2021-03-25T02:56:43+00:00","mainEntityOfPage":{"@id":"https:\/\/pynative.com\/python-exceptions\/"},"wordCount":2179,"commentCount":2,"publisher":{"@id":"https:\/\/pynative.com\/#\/schema\/person\/64b55d5bde2265918c5a9931de4de71f"},"image":{"@id":"https:\/\/pynative.com\/python-exceptions\/#primaryimage"},"thumbnailUrl":"https:\/\/pynative.com\/wp-content\/uploads\/2021\/03\/python_exception_handling.png","keywords":["Python Basics"],"articleSection":["Python","Python Basics"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/pynative.com\/python-exceptions\/#respond"]}],"accessibilityFeature":["tableOfContents"]},{"@type":"WebPage","@id":"https:\/\/pynative.com\/python-exceptions\/","url":"https:\/\/pynative.com\/python-exceptions\/","name":"Python Exceptions and Errors &#8211; PYnative","isPartOf":{"@id":"https:\/\/pynative.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/pynative.com\/python-exceptions\/#primaryimage"},"image":{"@id":"https:\/\/pynative.com\/python-exceptions\/#primaryimage"},"thumbnailUrl":"https:\/\/pynative.com\/wp-content\/uploads\/2021\/03\/python_exception_handling.png","datePublished":"2021-03-24T08:41:10+00:00","dateModified":"2021-03-25T02:56:43+00:00","description":"Learn Python Exceptions and Errors in depth. handling exception with try-except-finally block. Raise exceptions and create custom exceptions","breadcrumb":{"@id":"https:\/\/pynative.com\/python-exceptions\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/pynative.com\/python-exceptions\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/pynative.com\/python-exceptions\/#primaryimage","url":"https:\/\/pynative.com\/wp-content\/uploads\/2021\/03\/python_exception_handling.png","contentUrl":"https:\/\/pynative.com\/wp-content\/uploads\/2021\/03\/python_exception_handling.png","width":845,"height":446,"caption":"Python Exceptions"},{"@type":"BreadcrumbList","@id":"https:\/\/pynative.com\/python-exceptions\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/pynative.com\/"},{"@type":"ListItem","position":2,"name":"Python","item":"https:\/\/pynative.com\/python\/"},{"@type":"ListItem","position":3,"name":"Python Exceptions and Errors"}]},{"@type":"WebSite","@id":"https:\/\/pynative.com\/#website","url":"https:\/\/pynative.com\/","name":"PYnative","description":"Python Programming","publisher":{"@id":"https:\/\/pynative.com\/#\/schema\/person\/64b55d5bde2265918c5a9931de4de71f"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/pynative.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":["Person","Organization"],"@id":"https:\/\/pynative.com\/#\/schema\/person\/64b55d5bde2265918c5a9931de4de71f","name":"Vishal","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/pynative.com\/wp-content\/uploads\/2019\/01\/vishalHule.jpg","url":"https:\/\/pynative.com\/wp-content\/uploads\/2019\/01\/vishalHule.jpg","contentUrl":"https:\/\/pynative.com\/wp-content\/uploads\/2019\/01\/vishalHule.jpg","width":968,"height":1065,"caption":"Vishal"},"logo":{"@id":"https:\/\/pynative.com\/wp-content\/uploads\/2019\/01\/vishalHule.jpg"},"description":"Founder of PYnative.com. I am a Python developer and I love to write articles to help developers. | All the best for your future Python endeavors!","sameAs":["https:\/\/pynative.com"]}]}},"featured_image_src":"https:\/\/pynative.com\/wp-content\/uploads\/2021\/03\/python_exception_handling-600x400.png","featured_image_src_square":"https:\/\/pynative.com\/wp-content\/uploads\/2021\/03\/python_exception_handling-600x446.png","author_info":{"display_name":"Vishal","author_link":"https:\/\/pynative.com\/author\/vishal\/"},"_links":{"self":[{"href":"https:\/\/pynative.com\/wp-json\/wp\/v2\/posts\/9210","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/pynative.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/pynative.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/pynative.com\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/pynative.com\/wp-json\/wp\/v2\/comments?post=9210"}],"version-history":[{"count":0,"href":"https:\/\/pynative.com\/wp-json\/wp\/v2\/posts\/9210\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/pynative.com\/wp-json\/wp\/v2\/media\/9211"}],"wp:attachment":[{"href":"https:\/\/pynative.com\/wp-json\/wp\/v2\/media?parent=9210"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/pynative.com\/wp-json\/wp\/v2\/categories?post=9210"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/pynative.com\/wp-json\/wp\/v2\/tags?post=9210"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}