

{"id":6306,"date":"2018-01-23T09:01:16","date_gmt":"2018-01-23T03:31:16","guid":{"rendered":"https:\/\/data-flair.training\/blogs\/?p=6306"},"modified":"2026-04-24T14:24:55","modified_gmt":"2026-04-24T08:54:55","slug":"python-exception-handling","status":"publish","type":"post","link":"https:\/\/data-flair.training\/blogs\/python-exception-handling\/","title":{"rendered":"Python Exception Handling &#8211; Try\/Except Block, Finally Block"},"content":{"rendered":"<p>In our previous lesson on Errors and Exceptions in Python. Now, we are going to explore Python Exception Handling.<\/p>\n<p>Here, we will discuss try\/except blocks, finally blocks, and raise blocks. Along with this, we will learn how to define our own Python exception.<\/p>\n<p>So, let&#8217;s begin Exception Handling in Python.<\/p>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/01\/Exception-Handling-in-Python.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"wp-image-6307 size-full\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/01\/Exception-Handling-in-Python.jpg\" alt=\"Exception Handling in Python\" width=\"1200\" height=\"628\" srcset=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/01\/Exception-Handling-in-Python.jpg 1200w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/01\/Exception-Handling-in-Python-150x79.jpg 150w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/01\/Exception-Handling-in-Python-300x157.jpg 300w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/01\/Exception-Handling-in-Python-768x402.jpg 768w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/01\/Exception-Handling-in-Python-1024x536.jpg 1024w\" sizes=\"auto, (max-width: 1200px) 100vw, 1200px\" \/><\/a><\/p>\n<p>Python Exception Handling<\/p>\n<h3>What is Exception Handling in Python?<\/h3>\n<p>As we have already seen different types of exceptions in Python, let us see various ways for Python exception handling if we get any Python exception while programming in Python.<\/p>\n<h4>The try\/except blocks<\/h4>\n<p>When you think a part of your code might throw an exception, put it in a try block.<\/p>\n<p>Let us see a Python try-except exception example.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">try:\r\n            for i in range(3):\r\n                        print(3\/i)\r\nexcept:\r\n            print(\"You divided by 0\")\r\n     print(\u2018This prints because the exception was handled\u2019)<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>= RESTART: C:\\Users\\lifei\\AppData\\Local\\Programs\\Python\\Python36-32\\try2.py =<\/p>\n<p>You divided by 0<\/p>\n<p>This prints because the exception was handled<\/p>\n<\/div>\n<p>What follows is an except block. When you don\u2019t specify which exception to catch, it will catch any. In other words, this is generic for exceptions.<\/p>\n<p>When an exception is thrown in a try block, the interpreter looks for the except block following it. It will not execute the rest of the code in the try block.<\/p>\n<p>Python Exceptions are particularly useful when your code takes user input. You never know what the user will enter, and how it will mess with your code.<\/p>\n<h4>1. Python Multiple Excepts<\/h4>\n<p>It is possible to have multiple except blocks for one try block. Let us see Python multiple exception handling examples.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; a,b=1,0\r\n&gt;&gt;&gt; try:\r\n          print(a\/b)\r\n          print(\"This won't be printed\")\r\n          print('10'+10)\r\nexcept TypeError:\r\n          print(\"You added values of incompatible types\")\r\nexcept ZeroDivisionError:\r\n          print(\"You divided by 0\")<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>You divided by 0<\/p>\n<\/div>\n<p>When the interpreter encounters an exception, it checks the exception blocks associated with that try block.<\/p>\n<p>These except blocks may declare what kind of exceptions they handle. When the interpreter finds a matching exception, it executes that except block.<\/p>\n<p>In our example, the first statement under the try block gave us a ZeroDivisionError.<\/p>\n<p>We handled this in its except block, but the statements in the try block after the first one didn\u2019t execute.<\/p>\n<p>This is because once an exception is encountered, the statements after that in the try block are skipped.<\/p>\n<p>And if an appropriate except block or a generic except block isn\u2019t found, the exception isn\u2019t handled.<\/p>\n<p>In this case, the rest of the program won\u2019t run. But if you handle the exception, the code after the excepts and the finally block will run as expected.<\/p>\n<p>Let\u2019s try some code for this.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">a,b=1,0\r\ntry:\r\n   print(a\/b)\r\nexcept:\r\n   print(\"You can't divide by 0\")\r\nprint(\"Will this be printed?\")<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">== RESTART: C:\\Users\\lifei\\AppData\\Local\\Programs\\Python\\Python36-32\\try.py ==<br \/>\nYou can&#8217;t divide by 0<br \/>\nWill this be printed?<\/div>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt;<\/pre>\n<h4>2. Python Multiple Exception in one Except<\/h4>\n<p>You can also have one except block handle multiple exceptions. To do this, use parentheses. Without that, the interpreter will return a syntax error.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; try:\r\n      print('10'+10)\r\n      print(1\/0)\r\nexcept (TypeError,ZeroDivisionError):\r\n      print(\"Invalid input\")<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>Invalid input<\/p>\n<\/div>\n<h4>3. A Generic except After All Excepts<\/h4>\n<p>Finally, you can complement all specific except blocks with a generic except at the end.<\/p>\n<p>This block will serve to handle all exceptions that go undetected by the specific except blocks.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; try:\r\n           print('1'+1)\r\n           print(sum)\r\n           print(1\/0)\r\nexcept NameError:\r\n           print(\"sum does not exist\")\r\nexcept ZeroDivisionError:\r\n           print(\"Cannot divide by 0\")\r\nexcept:\r\n           print(\"Something went wrong\")<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>Something went wrong<\/p>\n<\/div>\n<p>Here, the first statement under the try block tries to concatenate a string to an int. This raises a TypeError.<\/p>\n<p>As the interpreter comes across this, it checks for an appropriate except block that handles this.<\/p>\n<p>Also, you can\u2019t put a statement between try and catch blocks.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">try:\r\n   print(\"1\")\r\nprint(\"2\")\r\nexcept:\r\n   print(\"3\")<\/pre>\n<p>This gives you a syntax error.<\/p>\n<p>But there can only be one generic or default except block for one try block. The following code gives us \u201cdefault \u2018except:\u2019 must be last\u201d:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">try:\r\n       print(1\/0)\r\nexcept:\r\n       raise\r\nexcept:\r\n       print(\"Raised exception caught\")\r\nfinally:\r\n       print(\"Okay\")\r\nprint(\"Bye\")<\/pre>\n<h3>Finally Block in Python<\/h3>\n<p>Optionally, you may include a finally exception block after the last except block. The code under this block executes in all circumstances.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; try:\r\n        print(1\/0)\r\nexcept ValueError:\r\n        print(\"This is a value error\")\r\nfinally:\r\n        print(\"This will print no matter what.\")<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">This will print no matter what.<br \/>\nTraceback (most recent call last):File &#8220;&lt;pyshell#113&gt;&#8221;, line 2, in &lt;module&gt;<br \/>\nprint(1\/0)<br \/>\nZeroDivisionError: division by zero<\/div>\n<p>Note that the Python exception message is printed after the finally block executes. Now you may think, why don\u2019t we just use a print statement instead?<\/p>\n<p>As you can see in the previous example, \u2018finally\u2019 runs even when we fail to catch the exception that occurs. Now what if an exception occurred in except?<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; try:\r\n        print(1\/0)\r\nexcept ZeroDivisionError:\r\n        print(2\/0)\r\nfinally:\r\n        print(\"Sorry, not happening\")<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>Sorry, not happening<\/p>\n<p>Traceback (most recent call last):File &#8220;&lt;pyshell#122&gt;&#8221;, line 2, in &lt;module&gt;<\/p>\n<p>print(1\/0)<\/p>\n<p>ZeroDivisionError: division by zero<\/p>\n<\/div>\n<p>During handling of the above exception, another exception occurred:<\/p>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>Traceback (most recent call last):File &#8220;&lt;pyshell#122&gt;&#8221;, line 4, in &lt;module&gt;<\/p>\n<p>print(2\/0)<\/p>\n<p>ZeroDivisionError: division by zero<\/p>\n<\/div>\n<p>So as you can see, the code under the finally block executes no matter what.<\/p>\n<h3>Raise Keyword in Python<\/h3>\n<p>Sometimes, you may want to deal with a situation by raising a certain exception. A simple print statement won\u2019t work here.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; raise ZeroDivisionError<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>Traceback (most recent call last):File &#8220;&lt;pyshell#132&gt;&#8221;, line 1, in &lt;module&gt;<\/p>\n<p>raise ZeroDivisionError<\/p>\n<p>ZeroDivisionError<\/p>\n<\/div>\n<p>Let\u2019s take our case of division.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; a,b=int(input()),int(input())<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>10<\/p>\n<\/div>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; if b==0:\r\n        raise ZeroDivisionError<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>Traceback (most recent call last):File &#8220;&lt;pyshell#140&gt;&#8221;, line 2, in &lt;module&gt;<\/p>\n<p>raise ZeroDivisionError<\/p>\n<p>ZeroDivisionError<\/p>\n<\/div>\n<p>Here, we convert the inputs a and b to integers. Then, we check if b is 0. In that case, we raise a ZeroDivisionError.<\/p>\n<p>Now what if we put this in try-except blocks? Let\u2019s make a .py file for it.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">a,b=int(input()),int(input())\r\ntry:\r\n       if b==0:\r\n             raise ZeroDivisionError\r\nexcept:\r\n   print(\"You divided by 0\")\r\nprint(\"Will this print?\")<\/pre>\n<p>When we run this using Fn+F5, we get the following <strong>output:<\/strong><\/p>\n<div class=\"code-output\">\n<p>= RESTART: C:\\Users\\lifei\\AppData\\Local\\Programs\\Python\\Python36-32\\try2.py =1<\/p>\n<p>0<\/p>\n<p>You divided by 0<\/p>\n<p>Will this print?<\/p>\n<\/div>\n<p>We\u2019ll take just one more example before moving on.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; raise KeyError<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>Traceback (most recent call last):File &#8220;&lt;pyshell#180&gt;&#8221;, line 1, in &lt;module&gt;<\/p>\n<p>raise KeyError<\/p>\n<p>KeyError<\/p>\n<\/div>\n<h4>1. Raise Without a Specified Exception in Python<\/h4>\n<p>It is possible to use the raise keyword without specifying what exception to raise. Then, it rethrows the exception that occurred.<\/p>\n<p>This is why you can only put it in an except block.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; try:\r\n         print('1'+1)\r\nexcept:\r\n         raise<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>Traceback (most recent call last):File &#8220;&lt;pyshell#152&gt;&#8221;, line 2, in &lt;module&gt;<\/p>\n<p>print(&#8216;1&#8217;+1)<\/p>\n<p>TypeError: must be str, not int<\/p>\n<\/div>\n<h4>2. Raise With an Argument in Python<\/h4>\n<p>Additionally, you can provide an argument to the specified exception in raise.<\/p>\n<p>You can do this to give out additional details about the exception.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; raise ValueError(\"Inappropriate value\")<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>Traceback (most recent call last):File &#8220;&lt;pyshell#156&gt;&#8221;, line 1, in &lt;module&gt;<\/p>\n<p>raise ValueError(&#8220;Inappropriate value&#8221;)<\/p>\n<p>ValueError: Inappropriate value<\/p>\n<\/div>\n<h3>Assertions in Python<\/h3>\n<p>An assertion is actually a sanity check for your cynical, paranoid soul.<\/p>\n<p>It takes an expression as an argument and raises a Python exception if the expression has a False Boolean value.<\/p>\n<p>Otherwise, it performs a No-operation (NOP).<\/p>\n<p><strong>Characteristics of assertion in Python:<\/strong><\/p>\n<ul>\n<li><strong>A sanity check:<\/strong> A quick check is done to make sure that the code is running exactly the way you expected or not.<\/li>\n<li><strong>True or False:<\/strong> If the condition is true, then the code runs properly. If the condition is false, then the program crashes immediately with an error.<\/li>\n<li><strong>Custom alarm:<\/strong> A short note can be added to the assertion so you know why the code has stopped.<\/li>\n<li><strong>Optional:<\/strong> You can tell Python to ignore all the assertions while running the final version to make it run a bit faster.<\/li>\n<\/ul>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; assert(True)\r\n&gt;&gt;&gt;<\/pre>\n<p>Now what if the expression was False?<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; assert(1==0)<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>Traceback (most recent call last):File &#8220;&lt;pyshell#157&gt;&#8221;, line 1, in &lt;module&gt;<\/p>\n<p>assert(1==0)<\/p>\n<p>AssertionError<\/p>\n<\/div>\n<p>Let\u2019s take another example, and let\u2019s create a .py file for that.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">try:\r\n       print(1)\r\n       assert 2+2==4\r\n       print(2)\r\n       assert 1+2==4\r\n       print(3)\r\nexcept:\r\n       print(\"An assert failed.\")\r\n       raise\r\nfinally:\r\n       print(\"Okay\")\r\nprint(\"Bye\")<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>= RESTART: C:\\Users\\lifei\\AppData\\Local\\Programs\\Python\\Python36-32\\try2.py =1<\/p>\n<p>2<\/p>\n<p>An assert failed.<\/p>\n<p>Okay<\/p>\n<p>Traceback (most recent call last):File &#8220;C:\\Users\\lifei\\AppData\\Local\\Programs\\Python\\Python36-32\\try2.py&#8221;, line 5, in &lt;module&gt;<\/p>\n<p>assert 1+2==4<\/p>\n<p>AssertionError<\/p>\n<\/div>\n<p>Interestingly, if you remove the raise from under the except block, this is the <strong>output:<\/strong><\/p>\n<div class=\"code-output\">\n<p>= RESTART: C:\\Users\\lifei\\AppData\\Local\\Programs\\Python\\Python36-32\\try2.py =1<\/p>\n<p>2<\/p>\n<p>An assert failed.<\/p>\n<p>Okay<\/p>\n<p>Bye<\/p>\n<\/div>\n<p>This is because when we \u2018raise\u2019 an exception, we aren\u2019t provisioning a handle for it.<\/p>\n<p>We can use assertions to check for valid input and output to functions.<\/p>\n<h4>1. A Second Argument to assert<\/h4>\n<p>You may optionally provide a second argument to give out some extra information about the problem.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; assert False,\"That's a problem\"<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>Traceback (most recent call last):File &#8220;&lt;pyshell#173&gt;&#8221;, line 1, in &lt;module&gt;<\/p>\n<p>assert False,&#8221;That&#8217;s a problem&#8221;<\/p>\n<p>AssertionError: That&#8217;s a problem<\/p>\n<\/div>\n<h3>Defining Your Own Exceptions in Python<\/h3>\n<p>Finally, we\u2019ll talk about creating our own exceptions. For this, we derive a new class from the Exception class.<\/p>\n<p>Later, we call it like any other exception.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">&gt;&gt;&gt; class MyError(Exception):\r\nprint(\"This is a problem\")\r\n&gt;&gt;&gt; raise MyError(\"MyError happened\")<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>Traceback (most recent call last):File &#8220;&lt;pyshell#179&gt;&#8221;, line 1, in &lt;module&gt;<\/p>\n<p>raise MyError(&#8220;MyError happened&#8221;)<\/p>\n<p>MyError: MyError happened<\/p>\n<\/div>\n<p>This was all about the Python Exception Handling Cheat Sheet.<\/p>\n<h3>Python Interview Questions on Exception Handling<\/h3>\n<ol>\n<li>What is Python exception handling? Explain with an example.<\/li>\n<li>Why is exception handling important in Python?<\/li>\n<li>How to handle multiple exceptions in Python?<\/li>\n<li>How does Python handle value exceptions?<\/li>\n<li>What is the purpose of try and catch in Python exception handling?<\/li>\n<\/ol>\n<h3>Conclusion<\/h3>\n<p>After this article, we hope you\u2019ll play safer with your code. This is because now you can\u00a0do Python Exception Handling, raise it, and even create your own.<\/p>\n<p>If you\u2019d like to add your own code on Python Exception Handling to the comments, we\u2019d love to hear it.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In our previous lesson on Errors and Exceptions in Python. Now, we are going to explore Python Exception Handling. Here, we will discuss try\/except blocks, finally blocks, and raise blocks. Along with this, we&#46;&#46;&#46;<\/p>\n","protected":false},"author":5,"featured_media":36073,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[46],"tags":[4432,4437,10520,10521],"class_list":["post-6306","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python","tag-exception-handling-in-python","tag-exception-in-python","tag-python-exception-handling","tag-python-exceptions"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.4 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Python Exception Handling - Try\/Except Block, Finally Block - DataFlair<\/title>\n<meta name=\"description\" content=\"Python Exception Handling - methods to do python exception handling, try cath block, finally block,assertions, Raise keyword, Define your own 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:\/\/data-flair.training\/blogs\/python-exception-handling\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Python Exception Handling - Try\/Except Block, Finally Block - DataFlair\" \/>\n<meta property=\"og:description\" content=\"Python Exception Handling - methods to do python exception handling, try cath block, finally block,assertions, Raise keyword, Define your own exceptions\" \/>\n<meta property=\"og:url\" content=\"https:\/\/data-flair.training\/blogs\/python-exception-handling\/\" \/>\n<meta property=\"og:site_name\" content=\"DataFlair\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/DataFlairWS\/\" \/>\n<meta property=\"article:published_time\" content=\"2018-01-23T03:31:16+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2026-04-24T08:54:55+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/01\/Exception-Handling-in-Python-1.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"DataFlair Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:site\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"DataFlair Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"7 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Python Exception Handling - Try\/Except Block, Finally Block - DataFlair","description":"Python Exception Handling - methods to do python exception handling, try cath block, finally block,assertions, Raise keyword, Define your own 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:\/\/data-flair.training\/blogs\/python-exception-handling\/","og_locale":"en_US","og_type":"article","og_title":"Python Exception Handling - Try\/Except Block, Finally Block - DataFlair","og_description":"Python Exception Handling - methods to do python exception handling, try cath block, finally block,assertions, Raise keyword, Define your own exceptions","og_url":"https:\/\/data-flair.training\/blogs\/python-exception-handling\/","og_site_name":"DataFlair","article_publisher":"https:\/\/www.facebook.com\/DataFlairWS\/","article_published_time":"2018-01-23T03:31:16+00:00","article_modified_time":"2026-04-24T08:54:55+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/01\/Exception-Handling-in-Python-1.jpg","type":"image\/jpeg"}],"author":"DataFlair Team","twitter_card":"summary_large_image","twitter_creator":"@DataFlairWS","twitter_site":"@DataFlairWS","twitter_misc":{"Written by":"DataFlair Team","Est. reading time":"7 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/data-flair.training\/blogs\/python-exception-handling\/#article","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/python-exception-handling\/"},"author":{"name":"DataFlair Team","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/7f83c342f5d1632d6f7b4b0b0f447823"},"headline":"Python Exception Handling &#8211; Try\/Except Block, Finally Block","datePublished":"2018-01-23T03:31:16+00:00","dateModified":"2026-04-24T08:54:55+00:00","mainEntityOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/python-exception-handling\/"},"wordCount":1532,"commentCount":3,"publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/python-exception-handling\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/01\/Exception-Handling-in-Python-1.jpg","keywords":["exception handling in python","exception in python","python exception handling","python exceptions"],"articleSection":["Python Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/data-flair.training\/blogs\/python-exception-handling\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/data-flair.training\/blogs\/python-exception-handling\/","url":"https:\/\/data-flair.training\/blogs\/python-exception-handling\/","name":"Python Exception Handling - Try\/Except Block, Finally Block - DataFlair","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/#website"},"primaryImageOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/python-exception-handling\/#primaryimage"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/python-exception-handling\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/01\/Exception-Handling-in-Python-1.jpg","datePublished":"2018-01-23T03:31:16+00:00","dateModified":"2026-04-24T08:54:55+00:00","description":"Python Exception Handling - methods to do python exception handling, try cath block, finally block,assertions, Raise keyword, Define your own exceptions","breadcrumb":{"@id":"https:\/\/data-flair.training\/blogs\/python-exception-handling\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/data-flair.training\/blogs\/python-exception-handling\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/python-exception-handling\/#primaryimage","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/01\/Exception-Handling-in-Python-1.jpg","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/01\/Exception-Handling-in-Python-1.jpg","width":1200,"height":628,"caption":"Python Exception Handling - Try\/Except Block, Finally Block, Raise Keyword"},{"@type":"BreadcrumbList","@id":"https:\/\/data-flair.training\/blogs\/python-exception-handling\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Blog Home","item":"https:\/\/data-flair.training\/blogs\/"},{"@type":"ListItem","position":2,"name":"Python Tutorials","item":"https:\/\/data-flair.training\/blogs\/category\/python\/"},{"@type":"ListItem","position":3,"name":"Python Exception Handling &#8211; Try\/Except Block, Finally Block"}]},{"@type":"WebSite","@id":"https:\/\/data-flair.training\/blogs\/#website","url":"https:\/\/data-flair.training\/blogs\/","name":"DataFlair","description":"Learn Today. Lead Tomorrow.","publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/data-flair.training\/blogs\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/data-flair.training\/blogs\/#organization","name":"DataFlair","url":"https:\/\/data-flair.training\/blogs\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","width":106,"height":48,"caption":"DataFlair"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/DataFlairWS\/","https:\/\/x.com\/DataFlairWS","https:\/\/www.linkedin.com\/company\/dataflair-web-services-pvt-ltd\/","https:\/\/www.youtube.com\/user\/DataFlairWS"]},{"@type":"Person","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/7f83c342f5d1632d6f7b4b0b0f447823","name":"DataFlair Team","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/4cf3a74600d131330b8c481d519afd1574093ed89f6d3396a95393ad223eb7cd?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/4cf3a74600d131330b8c481d519afd1574093ed89f6d3396a95393ad223eb7cd?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/4cf3a74600d131330b8c481d519afd1574093ed89f6d3396a95393ad223eb7cd?s=96&d=mm&r=g","caption":"DataFlair Team"},"description":"DataFlair Team creates expert-level guides on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our goal is to empower learners with easy-to-understand content. Explore our resources for career growth and practical learning.","url":"https:\/\/data-flair.training\/blogs\/author\/dfteam1\/"}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/6306","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/comments?post=6306"}],"version-history":[{"count":13,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/6306\/revisions"}],"predecessor-version":[{"id":147830,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/6306\/revisions\/147830"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media\/36073"}],"wp:attachment":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media?parent=6306"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/categories?post=6306"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/tags?post=6306"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}