{"id":79295,"date":"2020-07-06T09:00:06","date_gmt":"2020-07-06T03:30:06","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=79295"},"modified":"2020-07-06T09:00:06","modified_gmt":"2020-07-06T03:30:06","slug":"exception-handling-in-python","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/exception-handling-in-python\/","title":{"rendered":"Python Exceptions and Exception Handling"},"content":{"rendered":"<p>In case of an error, a good program should be able to recover from it. And if it is not possible to recover from the error, then your program should report it in an appropriate manner to the user. We\u2019ll learn what are Python Exceptions and how to write code for handling exceptions in Python.<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2020\/07\/exception-handling-in-python.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-79386\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2020\/07\/exception-handling-in-python.jpg\" alt=\"Python Exceptions\" width=\"802\" height=\"420\" \/><\/a><\/p>\n<h2>What are Python Exceptions?<\/h2>\n<p>When an error occurs at run-time, Python raises an exception. This is when your program crashes. That is, the interpreter terminates the execution of your program and displays an error message on the screen.<\/p>\n<p>But those big red errors don\u2019t look quite good on the screen, right?<\/p>\n<p>To avoid that, Python allows us to handle these exceptions in our own way so that our program doesn\u2019t terminate abruptly.<\/p>\n<h2>Catching Exceptions in Python<\/h2>\n<p>Python raises an exception when a run-time error occurs. If your program doesn\u2019t have code to take care of a raised exception, we say that the exception is uncaught. In that case, the interpreter will terminate your code and then display an error message.<\/p>\n<p>That said, we can also catch a raised exception. But catching an exception is not enough, we also have to decide what to do next. That is, we need to provide an alternate flow of execution. You can either run some other code in place of the crashed code. Or you can display a clean error message and terminate your application.<\/p>\n<p>This is the magic of Exception Handling, you can choose what happens when an exception occurs.<\/p>\n<h2>Let\u2019s code it &#8211; The try \u2026 except statement<\/h2>\n<p>At the core of it, the try \u2026 except statement allows you to react whenever a part of your code results in an exception.<\/p>\n<p>Place the code which can potentially raise an exception inside the try clause. And put the alternate code or a friendly error message inside the except clause.<\/p>\n<p>Let\u2019s look at an example where we try to open a file. But what if the file doesn\u2019t exist in our system? We don\u2019t want those big red scary error messages to pop up on the screen again, remember? So we\u2019ll indent the code for opening the file under the try statement. And the alternate code\/error message goes under the except clause.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">try:\n    f = open(\"file.txt\")\n    print(f.read())\n    \nexcept:\n    print(\"Error while opening the file\")\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">&#8220;Error while opening the file&#8221;<\/div>\n<p>The interpreter starts executing the code under the try clause.<\/p>\n<ul>\n<li>If no exception occurs, it ignores the except block and executes the rest of the code until it hits the end of the program.<\/li>\n<li>If an exception raises in the try clause, the flow of execution jumps to the except clause immediately.<\/li>\n<\/ul>\n<p><strong>We can also specify which exception our except clause will handle.<\/strong><\/p>\n<p><strong>Code to catch specific exception:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">try:\n    f = open(\"file.txt\")\n    print(f.read())\n    \nexcept FileNotFoundError:\n    print(\"Error while opening the file\")\n<\/pre>\n<p>This feature of handling specific exceptions is useful when multiple exceptions can occur in your try code. We can either use multiple except clauses in that case, or we can specify multiple exceptions in a single except clause.<\/p>\n<p><strong>Code to catch multiple exceptions using multiple except clauses:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">try:\n    x = int(input(\"Enter the numerator: \"))\n    y = int(input(\"Enter the denominator: \"))\n    print(\"The quotient is: \", x\/y)\n    \n\nexcept ZeroDivisionError:\n    print(\"Can't divide by zero\")\n\nexcept ValueError:\n    print(\"Please provide a valid integer value\")\n<\/pre>\n<p><strong>Code to catch multiple exceptions using a single except clause:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">try:\n    x = int(input(\"Enter the numerator: \"))\n    y = int(input(\"Enter the denominator: \"))\n    print(\"The quotient is: \", x\/y)\n    \n\nexcept (ZeroDivisionError, ValueError):\n    print(\"Please provide a valid integer value\")\n<\/pre>\n<p>&nbsp;<\/p>\n<h2>Adding Python Finally clause<\/h2>\n<p>It is optional to add the finally clause in Python. Even if an exception occurs or not, the code indented under the finally clause always executes.<\/p>\n<p>We usually use the finally clause to perform \u201cclean-up\u201d actions. For example, we need to close the file we were operating on in the try clause.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">try:\n    f = open(\"file.txt\")\n    print(f.read())\n    \nexcept FileNotFoundError:\n    print(\"Error while opening the file\")\n\nfinally:\n    f.close()\n<\/pre>\n<h2>Raising Exceptions in Python<\/h2>\n<p>One of the many superpowers of exception handling is that <strong>it can let us decide when to raise a specific exception in our code<\/strong>. We can also provide a custom message while raising an exception.<\/p>\n<p><strong>For Example<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">try:\n    x = input(\"Enter choice(yes\/no): \")\n    if x != 'yes' and x != 'no':\n        raise ValueError(\"Invalid choice. Please enter yes or no.\");\n\n\nexcept ValueError as e:\n    print(e)\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">Enter choice(yes\/no): ad<br \/>\nInvalid choice. Please enter yes or no.<br \/>\n&gt;&gt;&gt;<\/div>\n<h2>User-Defined Exceptions in Python<\/h2>\n<p>Python lets you create custom exceptions as well. You can define your own exception by creating a new class. Every user-defined exception class has to inherit from the Exception class.<\/p>\n<p><strong>Example code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">class MyException(Exception):\n    pass\n<\/pre>\n<p>That\u2019s literally all you need to do for creating your own exception! Now we have a custom exception \u201cMyException\u201d. We can raise this exception in our try clause. For Example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">class MyException(Exception):\n    pass\n\ntry:\n    my_list = [1, 2, 3, 4, 5]\n    x = int(input(\"Enter an integer: \"))\n    if x not in my_list:\n        raise MyException\n\nexcept MyException:\n    print(\"The number you entered is not present within the list.\")\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">Enter an integer: 7<br \/>\nThe number you entered is not in the list.<\/div>\n<h2>Summary<\/h2>\n<p>This brings up to the end of the article. We learned what exceptions are and how we can handle them. We also looked at various ways of using the try \u2026 except clause. We learned all about raising and catching exceptions. We got to know how important the finally clause can be at times. And lastly, we saw how we can create user-defined exceptions.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In case of an error, a good program should be able to recover from it. And if it is not possible to recover from the error, then your program should report it in an&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":79386,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1053],"tags":[1535,2992],"class_list":["post-79295","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python","tag-python-exception-handling","tag-python-exceptions"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Python Exceptions and Exception Handling - TechVidvan<\/title>\n<meta name=\"description\" content=\"Learn what are Python Exceptions, Catching Exceptions in Python, try-except statement, finally clause, Raising Exceptions, User-defined exceptions etc\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/techvidvan.com\/tutorials\/exception-handling-in-python\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Python Exceptions and Exception Handling - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"Learn what are Python Exceptions, Catching Exceptions in Python, try-except statement, finally clause, Raising Exceptions, User-defined exceptions etc\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/exception-handling-in-python\/\" \/>\n<meta property=\"og:site_name\" content=\"TechVidvan\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/TechVidvan\/\" \/>\n<meta property=\"article:published_time\" content=\"2020-07-06T03:30:06+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/07\/exception-handling-in-python.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"802\" \/>\n\t<meta property=\"og:image:height\" content=\"420\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"TechVidvan Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:site\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"TechVidvan Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"5 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Python Exceptions and Exception Handling - TechVidvan","description":"Learn what are Python Exceptions, Catching Exceptions in Python, try-except statement, finally clause, Raising Exceptions, User-defined exceptions etc","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:\/\/techvidvan.com\/tutorials\/exception-handling-in-python\/","og_locale":"en_US","og_type":"article","og_title":"Python Exceptions and Exception Handling - TechVidvan","og_description":"Learn what are Python Exceptions, Catching Exceptions in Python, try-except statement, finally clause, Raising Exceptions, User-defined exceptions etc","og_url":"https:\/\/techvidvan.com\/tutorials\/exception-handling-in-python\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2020-07-06T03:30:06+00:00","og_image":[{"width":802,"height":420,"url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/07\/exception-handling-in-python.jpg","type":"image\/jpeg"}],"author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@vidvantech","twitter_site":"@vidvantech","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"5 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/techvidvan.com\/tutorials\/exception-handling-in-python\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/exception-handling-in-python\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"Python Exceptions and Exception Handling","datePublished":"2020-07-06T03:30:06+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/exception-handling-in-python\/"},"wordCount":776,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/exception-handling-in-python\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/07\/exception-handling-in-python.jpg","keywords":["python exception handling","python exceptions"],"articleSection":["Python Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/exception-handling-in-python\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/exception-handling-in-python\/","url":"https:\/\/techvidvan.com\/tutorials\/exception-handling-in-python\/","name":"Python Exceptions and Exception Handling - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/exception-handling-in-python\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/exception-handling-in-python\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/07\/exception-handling-in-python.jpg","datePublished":"2020-07-06T03:30:06+00:00","description":"Learn what are Python Exceptions, Catching Exceptions in Python, try-except statement, finally clause, Raising Exceptions, User-defined exceptions etc","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/exception-handling-in-python\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/exception-handling-in-python\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/exception-handling-in-python\/#primaryimage","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/07\/exception-handling-in-python.jpg","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/07\/exception-handling-in-python.jpg","width":802,"height":420,"caption":"Python Exceptions"},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/exception-handling-in-python\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"Python Exceptions and Exception Handling"}]},{"@type":"WebSite","@id":"https:\/\/techvidvan.com\/tutorials\/#website","url":"https:\/\/techvidvan.com\/tutorials\/","name":"TechVidvan Blogs","description":"","publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/techvidvan.com\/tutorials\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/techvidvan.com\/tutorials\/#organization","name":"TechVidvan","url":"https:\/\/techvidvan.com\/tutorials\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","width":200,"height":50,"caption":"TechVidvan"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/TechVidvan\/","https:\/\/x.com\/vidvantech"]},{"@type":"Person","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22","name":"TechVidvan Team","description":"The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today\u2019s tech industry."}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/79295","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/comments?post=79295"}],"version-history":[{"count":0,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/79295\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media\/79386"}],"wp:attachment":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media?parent=79295"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=79295"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=79295"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}