{"id":4908,"date":"2023-12-14T15:54:25","date_gmt":"2023-12-14T15:54:25","guid":{"rendered":"https:\/\/reviewnprep.com\/blog\/?p=4908"},"modified":"2023-12-11T01:17:23","modified_gmt":"2023-12-11T01:17:23","slug":"mastering-exception-handling-in-python-real-life-examples-and-best-practices","status":"publish","type":"post","link":"https:\/\/reviewnprep.com\/blog\/mastering-exception-handling-in-python-real-life-examples-and-best-practices\/","title":{"rendered":"Mastering Exception Handling in Python: Real-Life Examples and Best Practices"},"content":{"rendered":"\n<p>Welcome to the beginner&#8217;s guide to exception handling in Python! As Python continues to dominate the programming world, it&#8217;s essential for developers of all levels to master the art of handling exceptions effectively. Whether you&#8217;re just starting out or looking to refresh your skills, this comprehensive guide will take you through the ins and outs of exception handling in Python, using practical examples to bring the concepts to life.<\/p>\n\n\n\n<p>Exception handling plays a crucial role in writing reliable and robust code, ensuring that your programs gracefully handle unexpected errors and prevent crashes. In this guide, we&#8217;ll dive deep into the world of exceptions, exploring the different types of exceptions, how to raise and handle them, and the best practices for error handling in Python.<\/p>\n\n\n\n<p>Through a series of practical examples, you&#8217;ll gain hands-on experience in dealing with common exceptions, such as ValueError, FileNotFoundError, and IndexError. By the end of this guide, you&#8217;ll have the confidence and skills to tackle any unforeseen errors that come your way, making your Python programs more resilient and user-friendly.<\/p>\n\n\n\n<p>So let&#8217;s get started on this exception handling journey and level up your Python coding skills!<\/p>\n\n\n\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_66_1 counter-hierarchy ez-toc-counter ez-toc-grey ez-toc-container-direction\">\n<p class=\"ez-toc-title\">Table of Contents<\/p>\n<label for=\"ez-toc-cssicon-toggle-item-69d4af5e1f876\" class=\"ez-toc-cssicon-toggle-label\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #999;color:#999\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewBox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #999;color:#999\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewBox=\"0 0 24 24\" version=\"1.2\" baseProfile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/label><input type=\"checkbox\"  id=\"ez-toc-cssicon-toggle-item-69d4af5e1f876\"  aria-label=\"Toggle\" \/><nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/reviewnprep.com\/blog\/mastering-exception-handling-in-python-real-life-examples-and-best-practices\/#Understanding_the_Basics_of_Exceptions\" title=\"Understanding the Basics of Exceptions\">Understanding the Basics of Exceptions<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/reviewnprep.com\/blog\/mastering-exception-handling-in-python-real-life-examples-and-best-practices\/#Common_Types_of_Exceptions_in_Python\" title=\"Common Types of Exceptions in Python\">Common Types of Exceptions in Python<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/reviewnprep.com\/blog\/mastering-exception-handling-in-python-real-life-examples-and-best-practices\/#Handling_Exceptions_using_Try-Except_Blocks\" title=\"Handling Exceptions using Try-Except Blocks\">Handling Exceptions using Try-Except Blocks<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/reviewnprep.com\/blog\/mastering-exception-handling-in-python-real-life-examples-and-best-practices\/#Using_Multiple_Except_Blocks_for_Different_Types_of_Exceptions\" title=\"Using Multiple Except Blocks for Different Types of Exceptions\">Using Multiple Except Blocks for Different Types of Exceptions<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/reviewnprep.com\/blog\/mastering-exception-handling-in-python-real-life-examples-and-best-practices\/#The_Else_Clause_and_Finally_Clause_in_Exception_Handling\" title=\"The Else Clause and Finally Clause in Exception Handling\">The Else Clause and Finally Clause in Exception Handling<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/reviewnprep.com\/blog\/mastering-exception-handling-in-python-real-life-examples-and-best-practices\/#Raising_and_Catching_Custom_Exceptions\" title=\"Raising and Catching Custom Exceptions\">Raising and Catching Custom Exceptions<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/reviewnprep.com\/blog\/mastering-exception-handling-in-python-real-life-examples-and-best-practices\/#Best_Practices_for_Exception_Handling_in_Python\" title=\"Best Practices for Exception Handling in Python\">Best Practices for Exception Handling in Python<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/reviewnprep.com\/blog\/mastering-exception-handling-in-python-real-life-examples-and-best-practices\/#Practical_Examples_of_Exception_Handling_in_Python\" title=\"Practical Examples of Exception Handling in Python\">Practical Examples of Exception Handling in Python<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-9\" href=\"https:\/\/reviewnprep.com\/blog\/mastering-exception-handling-in-python-real-life-examples-and-best-practices\/#Conclusion\" title=\"Conclusion\">Conclusion<\/a><\/li><\/ul><\/nav><\/div>\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Understanding_the_Basics_of_Exceptions\"><\/span>Understanding the Basics of Exceptions<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Exceptions are error conditions that disrupt the normal flow of a program. They can occur due to a wide range of reasons, such as invalid input, file operations, or unexpected issues during execution.<\/p>\n\n\n\n<p>These exceptions halt the normal flow of the program. Without exception handling, our Python scripts would crash whenever they encounter an error condition. By leveraging built-in exception handling tools like the try-except block, we can account for potential exceptions and take appropriate actions.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Common_Types_of_Exceptions_in_Python\"><\/span>Common Types of Exceptions in Python<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Python has a wide range of built-in exception classes for different types of errors:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong><code>ImportError<\/code><\/strong> &#8211; Raised when a module\/library cannot be imported<\/li>\n\n\n\n<li><strong><code>IndexError<\/code><\/strong> &#8211; Occurs when trying to access an invalid index in a list, tuple, etc<\/li>\n\n\n\n<li><strong><code>NameError<\/code><\/strong> &#8211; Happens when using an undeclared variable<\/li>\n\n\n\n<li><strong><code>TypeError<\/code><\/strong> &#8211; Indicates two incompatible types are mixed in an operation<\/li>\n\n\n\n<li><strong><code>ValueError<\/code><\/strong> &#8211; Occurs when built-in functions receive inappropriate arguments<\/li>\n\n\n\n<li><strong><code>ZeroDivisionError<\/code><\/strong> &#8211; Thrown when dividing by zero<\/li>\n\n\n\n<li><strong><code>FileNotFoundError<\/code><\/strong> &#8211; Raised when a file cannot be found at a specified path<\/li>\n\n\n\n<li><strong><code>KeyboardInterruption<\/code><\/strong> &#8211; Called on pressing Ctrl+C keys<\/li>\n\n\n\n<li><code><strong>SyntaxError<\/strong><\/code>: Raised for syntax errors.<\/li>\n<\/ul>\n\n\n\n<p>And many more specialized exceptions&#8230;<\/p>\n\n\n\n<p>Being aware of common error types helps write code that catches the exceptions specific to our program logic and use case.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Handling_Exceptions_using_Try-Except_Blocks\"><\/span>Handling Exceptions using Try-Except Blocks<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>The basic structure for handling exceptions in Python is the <code>try-except<\/code> block. It allows you to catch and handle exceptions gracefully:<\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#22272e\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"try:\n    # Code that may raise an exception\n    result = 10 \/ 0\nexcept ZeroDivisionError:\n    # Handle the specific exception\n    print(&quot;Cannot divide by zero&quot;)\" style=\"color:#adbac7;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki github-dark-dimmed\" style=\"background-color: #22272e\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #F47067\">try<\/span><span style=\"color: #ADBAC7\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">    <\/span><span style=\"color: #768390\"># Code that may raise an exception<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">    result <\/span><span style=\"color: #F47067\">=<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #6CB6FF\">10<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F47067\">\/<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #6CB6FF\">0<\/span><\/span>\n<span class=\"line\"><span style=\"color: #F47067\">except<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #6CB6FF\">ZeroDivisionError<\/span><span style=\"color: #ADBAC7\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">    <\/span><span style=\"color: #768390\"># Handle the specific exception<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">    <\/span><span style=\"color: #6CB6FF\">print<\/span><span style=\"color: #ADBAC7\">(<\/span><span style=\"color: #96D0FF\">&quot;Cannot divide by zero&quot;<\/span><span style=\"color: #ADBAC7\">)<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p>The code inside the try clause is executed. If that code raises no exceptions, then no output from except clause is generated. But if an exception occurs, it is caught and the except block with the matching exception type is executed.<\/p>\n\n\n\n<p>We can thus anticipate errors and ensure the program doesn&#8217;t crash if things go wrong.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Using_Multiple_Except_Blocks_for_Different_Types_of_Exceptions\"><\/span>Using Multiple Except Blocks for Different Types of Exceptions<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>You can use multiple <code>except<\/code> blocks to handle different types of exceptions:<\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#22272e\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"try:\n   f = open(&quot;data.txt&quot;)\n   num = int(input(&quot;Enter a number: &quot;))\n   value = 10 \/ num\n\nexcept FileNotFoundError:\n   print(&quot;The file was not found!&quot;)\n   \nexcept ValueError:\n   print(&quot;Please enter a number.&quot;)\n   \nexcept ZeroDivisionError:\n   print(&quot;Cannot divide by zero!&quot;)\" style=\"color:#adbac7;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki github-dark-dimmed\" style=\"background-color: #22272e\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #F47067\">try<\/span><span style=\"color: #ADBAC7\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">   f <\/span><span style=\"color: #F47067\">=<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #6CB6FF\">open<\/span><span style=\"color: #ADBAC7\">(<\/span><span style=\"color: #96D0FF\">&quot;data.txt&quot;<\/span><span style=\"color: #ADBAC7\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">   num <\/span><span style=\"color: #F47067\">=<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #6CB6FF\">int<\/span><span style=\"color: #ADBAC7\">(<\/span><span style=\"color: #6CB6FF\">input<\/span><span style=\"color: #ADBAC7\">(<\/span><span style=\"color: #96D0FF\">&quot;Enter a number: &quot;<\/span><span style=\"color: #ADBAC7\">))<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">   value <\/span><span style=\"color: #F47067\">=<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #6CB6FF\">10<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F47067\">\/<\/span><span style=\"color: #ADBAC7\"> num<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #F47067\">except<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #6CB6FF\">FileNotFoundError<\/span><span style=\"color: #ADBAC7\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">   <\/span><span style=\"color: #6CB6FF\">print<\/span><span style=\"color: #ADBAC7\">(<\/span><span style=\"color: #96D0FF\">&quot;The file was not found!&quot;<\/span><span style=\"color: #ADBAC7\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">   <\/span><\/span>\n<span class=\"line\"><span style=\"color: #F47067\">except<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #6CB6FF\">ValueError<\/span><span style=\"color: #ADBAC7\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">   <\/span><span style=\"color: #6CB6FF\">print<\/span><span style=\"color: #ADBAC7\">(<\/span><span style=\"color: #96D0FF\">&quot;Please enter a number.&quot;<\/span><span style=\"color: #ADBAC7\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">   <\/span><\/span>\n<span class=\"line\"><span style=\"color: #F47067\">except<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #6CB6FF\">ZeroDivisionError<\/span><span style=\"color: #ADBAC7\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">   <\/span><span style=\"color: #6CB6FF\">print<\/span><span style=\"color: #ADBAC7\">(<\/span><span style=\"color: #96D0FF\">&quot;Cannot divide by zero!&quot;<\/span><span style=\"color: #ADBAC7\">)<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p>Having specific except blocks allow handling exceptions differently instead of generic handling.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"The_Else_Clause_and_Finally_Clause_in_Exception_Handling\"><\/span>The Else Clause and Finally Clause in Exception Handling<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>The <code>else<\/code> clause is executed if the code in the <code>try<\/code> block doesn&#8217;t raise any exceptions. The <code>finally<\/code> clause is always executed, regardless of whether an exception occurred or not:<\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#22272e\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"try:\n    # Code that may raise an exception\n    value = int(input(&quot;Enter a number: &quot;))\n    result = 10 \/ value\nexcept ValueError:\n    print(&quot;Invalid input. Please enter a valid number.&quot;)\nexcept ZeroDivisionError:\n    print(&quot;Cannot divide by zero&quot;)\nelse:\n    print(&quot;Division successful&quot;)\nfinally:\n    print(&quot;This will always be executed&quot;)\" style=\"color:#adbac7;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki github-dark-dimmed\" style=\"background-color: #22272e\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #F47067\">try<\/span><span style=\"color: #ADBAC7\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">    <\/span><span style=\"color: #768390\"># Code that may raise an exception<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">    value <\/span><span style=\"color: #F47067\">=<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #6CB6FF\">int<\/span><span style=\"color: #ADBAC7\">(<\/span><span style=\"color: #6CB6FF\">input<\/span><span style=\"color: #ADBAC7\">(<\/span><span style=\"color: #96D0FF\">&quot;Enter a number: &quot;<\/span><span style=\"color: #ADBAC7\">))<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">    result <\/span><span style=\"color: #F47067\">=<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #6CB6FF\">10<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F47067\">\/<\/span><span style=\"color: #ADBAC7\"> value<\/span><\/span>\n<span class=\"line\"><span style=\"color: #F47067\">except<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #6CB6FF\">ValueError<\/span><span style=\"color: #ADBAC7\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">    <\/span><span style=\"color: #6CB6FF\">print<\/span><span style=\"color: #ADBAC7\">(<\/span><span style=\"color: #96D0FF\">&quot;Invalid input. Please enter a valid number.&quot;<\/span><span style=\"color: #ADBAC7\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #F47067\">except<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #6CB6FF\">ZeroDivisionError<\/span><span style=\"color: #ADBAC7\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">    <\/span><span style=\"color: #6CB6FF\">print<\/span><span style=\"color: #ADBAC7\">(<\/span><span style=\"color: #96D0FF\">&quot;Cannot divide by zero&quot;<\/span><span style=\"color: #ADBAC7\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #F47067\">else<\/span><span style=\"color: #ADBAC7\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">    <\/span><span style=\"color: #6CB6FF\">print<\/span><span style=\"color: #ADBAC7\">(<\/span><span style=\"color: #96D0FF\">&quot;Division successful&quot;<\/span><span style=\"color: #ADBAC7\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #F47067\">finally<\/span><span style=\"color: #ADBAC7\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">    <\/span><span style=\"color: #6CB6FF\">print<\/span><span style=\"color: #ADBAC7\">(<\/span><span style=\"color: #96D0FF\">&quot;This will always be executed&quot;<\/span><span style=\"color: #ADBAC7\">)<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p>The finally clause helps execute cleanup code like closing files, connections etc irrespective of exceptions.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Raising_and_Catching_Custom_Exceptions\"><\/span>Raising and Catching Custom Exceptions<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Along with built-in exceptions, we can define custom exception classes by subclassing Exception:<\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#22272e\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"class InvalidInputError(Exception):\n   pass\n\nnum = int(input(&quot;Please enter a number: &quot;))\n\nif num &lt; 0:\n   raise InvalidInputError(&quot;Number cannot be negative!&quot;)\" style=\"color:#adbac7;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki github-dark-dimmed\" style=\"background-color: #22272e\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #F47067\">class<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F69D50\">InvalidInputError<\/span><span style=\"color: #ADBAC7\">(<\/span><span style=\"color: #6CB6FF\">Exception<\/span><span style=\"color: #ADBAC7\">):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">   <\/span><span style=\"color: #F47067\">pass<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">num <\/span><span style=\"color: #F47067\">=<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #6CB6FF\">int<\/span><span style=\"color: #ADBAC7\">(<\/span><span style=\"color: #6CB6FF\">input<\/span><span style=\"color: #ADBAC7\">(<\/span><span style=\"color: #96D0FF\">&quot;Please enter a number: &quot;<\/span><span style=\"color: #ADBAC7\">))<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #F47067\">if<\/span><span style=\"color: #ADBAC7\"> num <\/span><span style=\"color: #F47067\">&lt;<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #6CB6FF\">0<\/span><span style=\"color: #ADBAC7\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">   <\/span><span style=\"color: #F47067\">raise<\/span><span style=\"color: #ADBAC7\"> InvalidInputError(<\/span><span style=\"color: #96D0FF\">&quot;Number cannot be negative!&quot;<\/span><span style=\"color: #ADBAC7\">)<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p>We can raise exceptions manually with raise and catch them later:<\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#22272e\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"try:\n   num = int(input(&quot;Please enter a number: &quot;))\n   if num &lt; 0:\n      raise InvalidInputError(&quot;Negative number not allowed!&quot;)\nexcept InvalidInputError as e:\n    print(e)\" style=\"color:#adbac7;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki github-dark-dimmed\" style=\"background-color: #22272e\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #F47067\">try<\/span><span style=\"color: #ADBAC7\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">   num <\/span><span style=\"color: #F47067\">=<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #6CB6FF\">int<\/span><span style=\"color: #ADBAC7\">(<\/span><span style=\"color: #6CB6FF\">input<\/span><span style=\"color: #ADBAC7\">(<\/span><span style=\"color: #96D0FF\">&quot;Please enter a number: &quot;<\/span><span style=\"color: #ADBAC7\">))<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">   <\/span><span style=\"color: #F47067\">if<\/span><span style=\"color: #ADBAC7\"> num <\/span><span style=\"color: #F47067\">&lt;<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #6CB6FF\">0<\/span><span style=\"color: #ADBAC7\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">      <\/span><span style=\"color: #F47067\">raise<\/span><span style=\"color: #ADBAC7\"> InvalidInputError(<\/span><span style=\"color: #96D0FF\">&quot;Negative number not allowed!&quot;<\/span><span style=\"color: #ADBAC7\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #F47067\">except<\/span><span style=\"color: #ADBAC7\"> InvalidInputError <\/span><span style=\"color: #F47067\">as<\/span><span style=\"color: #ADBAC7\"> e:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">    <\/span><span style=\"color: #6CB6FF\">print<\/span><span style=\"color: #ADBAC7\">(e)<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p>This makes code more readable by separating custom error scenarios.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Best_Practices_for_Exception_Handling_in_Python\"><\/span>Best Practices for Exception Handling in Python<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Here are some best practices to write clean, robust exception handling:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Keep try blocks small and focused to properly handle exceptions<\/li>\n\n\n\n<li>Catch specific exceptions instead of generic Exception class to differentiate errors<\/li>\n\n\n\n<li>Print custom error messages from except blocks upon failures<\/li>\n\n\n\n<li>Use finally clause to execute sections of cleanup code reliably<\/li>\n\n\n\n<li>Define custom exception classes to match application scenarios<\/li>\n\n\n\n<li><strong>Use <code>try-except<\/code> blocks only where needed.<\/strong>\n<ul class=\"wp-block-list\">\n<li>Don&#8217;t wrap your entire code in a massive <code>try-except<\/code> block; limit it to potential error-prone sections.<\/li>\n\n\n\n<li>Don&#8217;t overuse try-except blocks in business logic to avoid hiding real issues<\/li>\n\n\n\n<li>Avoid using <code>except:<\/code> without specifying the exception type, as it can catch unintended errors.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li>Use logging to record exceptions for later analysis.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Practical_Examples_of_Exception_Handling_in_Python\"><\/span>Practical Examples of Exception Handling in Python<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Let&#8217;s apply exception handling concepts to some real-world examples:<\/p>\n\n\n\n<p><strong>Example 1<\/strong> &#8211; Handling invalid user input:<\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#22272e\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"while True:\n   try: \n      number = int(input(&quot;Please enter a number: &quot;))\n   except ValueError:\n      print(&quot;You did not enter a valid number!&quot;)\n      continue\n   else:\n      print(f&quot;The square of your number is {number**2}&quot;)\n      break\" style=\"color:#adbac7;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki github-dark-dimmed\" style=\"background-color: #22272e\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #F47067\">while<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #6CB6FF\">True<\/span><span style=\"color: #ADBAC7\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">   <\/span><span style=\"color: #F47067\">try<\/span><span style=\"color: #ADBAC7\">: <\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">      number <\/span><span style=\"color: #F47067\">=<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #6CB6FF\">int<\/span><span style=\"color: #ADBAC7\">(<\/span><span style=\"color: #6CB6FF\">input<\/span><span style=\"color: #ADBAC7\">(<\/span><span style=\"color: #96D0FF\">&quot;Please enter a number: &quot;<\/span><span style=\"color: #ADBAC7\">))<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">   <\/span><span style=\"color: #F47067\">except<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #6CB6FF\">ValueError<\/span><span style=\"color: #ADBAC7\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">      <\/span><span style=\"color: #6CB6FF\">print<\/span><span style=\"color: #ADBAC7\">(<\/span><span style=\"color: #96D0FF\">&quot;You did not enter a valid number!&quot;<\/span><span style=\"color: #ADBAC7\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">      <\/span><span style=\"color: #F47067\">continue<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">   <\/span><span style=\"color: #F47067\">else<\/span><span style=\"color: #ADBAC7\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">      <\/span><span style=\"color: #6CB6FF\">print<\/span><span style=\"color: #ADBAC7\">(<\/span><span style=\"color: #F47067\">f<\/span><span style=\"color: #96D0FF\">&quot;The square of your number is <\/span><span style=\"color: #F47067\">{<\/span><span style=\"color: #ADBAC7\">number<\/span><span style=\"color: #F47067\">**<\/span><span style=\"color: #6CB6FF\">2<\/span><span style=\"color: #F47067\">}<\/span><span style=\"color: #96D0FF\">&quot;<\/span><span style=\"color: #ADBAC7\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">      <\/span><span style=\"color: #F47067\">break<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p><strong>Example 2<\/strong> &#8211; Catching different exception types:<\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#22272e\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"import sys\n\ntry:\n   f = open(&quot;data.txt&quot;)\n   x = 10\/0\nexcept FileNotFoundError:\n   print(&quot;The file was not found!&quot;)\nexcept ZeroDivisionError:\n   print(&quot;Cannot divide by 0!&quot;)\nexcept:\n   print(f&quot;Unknown error: {sys.exc_info()[1]}&quot;)\" style=\"color:#adbac7;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki github-dark-dimmed\" style=\"background-color: #22272e\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #F47067\">import<\/span><span style=\"color: #ADBAC7\"> sys<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #F47067\">try<\/span><span style=\"color: #ADBAC7\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">   f <\/span><span style=\"color: #F47067\">=<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #6CB6FF\">open<\/span><span style=\"color: #ADBAC7\">(<\/span><span style=\"color: #96D0FF\">&quot;data.txt&quot;<\/span><span style=\"color: #ADBAC7\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">   x <\/span><span style=\"color: #F47067\">=<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #6CB6FF\">10<\/span><span style=\"color: #F47067\">\/<\/span><span style=\"color: #6CB6FF\">0<\/span><\/span>\n<span class=\"line\"><span style=\"color: #F47067\">except<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #6CB6FF\">FileNotFoundError<\/span><span style=\"color: #ADBAC7\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">   <\/span><span style=\"color: #6CB6FF\">print<\/span><span style=\"color: #ADBAC7\">(<\/span><span style=\"color: #96D0FF\">&quot;The file was not found!&quot;<\/span><span style=\"color: #ADBAC7\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #F47067\">except<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #6CB6FF\">ZeroDivisionError<\/span><span style=\"color: #ADBAC7\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">   <\/span><span style=\"color: #6CB6FF\">print<\/span><span style=\"color: #ADBAC7\">(<\/span><span style=\"color: #96D0FF\">&quot;Cannot divide by 0!&quot;<\/span><span style=\"color: #ADBAC7\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #F47067\">except<\/span><span style=\"color: #ADBAC7\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">   <\/span><span style=\"color: #6CB6FF\">print<\/span><span style=\"color: #ADBAC7\">(<\/span><span style=\"color: #F47067\">f<\/span><span style=\"color: #96D0FF\">&quot;Unknown error: <\/span><span style=\"color: #F47067\">{<\/span><span style=\"color: #ADBAC7\">sys.exc_info()[<\/span><span style=\"color: #6CB6FF\">1<\/span><span style=\"color: #ADBAC7\">]<\/span><span style=\"color: #F47067\">}<\/span><span style=\"color: #96D0FF\">&quot;<\/span><span style=\"color: #ADBAC7\">)<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p><strong>Example 3<\/strong> &#8211; Defining custom exception class:<\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#22272e\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"class NegativeNumberError(Exception):\n   pass\n   \ndef calculate_square(num):\n   if num &lt; 0:\n      raise NegativeNumberError(&quot;Negative numbers unacceptable&quot;)\n   return num**2\n\nnum = -6   \ntry:\n   result = calculate_square(num)\nexcept NegativeNumberError as e:\n   print(e)\" style=\"color:#adbac7;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki github-dark-dimmed\" style=\"background-color: #22272e\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #F47067\">class<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F69D50\">NegativeNumberError<\/span><span style=\"color: #ADBAC7\">(<\/span><span style=\"color: #6CB6FF\">Exception<\/span><span style=\"color: #ADBAC7\">):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">   <\/span><span style=\"color: #F47067\">pass<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">   <\/span><\/span>\n<span class=\"line\"><span style=\"color: #F47067\">def<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #DCBDFB\">calculate_square<\/span><span style=\"color: #ADBAC7\">(num):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">   <\/span><span style=\"color: #F47067\">if<\/span><span style=\"color: #ADBAC7\"> num <\/span><span style=\"color: #F47067\">&lt;<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #6CB6FF\">0<\/span><span style=\"color: #ADBAC7\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">      <\/span><span style=\"color: #F47067\">raise<\/span><span style=\"color: #ADBAC7\"> NegativeNumberError(<\/span><span style=\"color: #96D0FF\">&quot;Negative numbers unacceptable&quot;<\/span><span style=\"color: #ADBAC7\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">   <\/span><span style=\"color: #F47067\">return<\/span><span style=\"color: #ADBAC7\"> num<\/span><span style=\"color: #F47067\">**<\/span><span style=\"color: #6CB6FF\">2<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">num <\/span><span style=\"color: #F47067\">=<\/span><span style=\"color: #ADBAC7\"> <\/span><span style=\"color: #F47067\">-<\/span><span style=\"color: #6CB6FF\">6<\/span><span style=\"color: #ADBAC7\">   <\/span><\/span>\n<span class=\"line\"><span style=\"color: #F47067\">try<\/span><span style=\"color: #ADBAC7\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">   result <\/span><span style=\"color: #F47067\">=<\/span><span style=\"color: #ADBAC7\"> calculate_square(num)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #F47067\">except<\/span><span style=\"color: #ADBAC7\"> NegativeNumberError <\/span><span style=\"color: #F47067\">as<\/span><span style=\"color: #ADBAC7\"> e:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #ADBAC7\">   <\/span><span style=\"color: #6CB6FF\">print<\/span><span style=\"color: #ADBAC7\">(e)<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Conclusion\"><\/span>Conclusion<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Mastering the basics of exception handling in Python is crucial for writing robust and error-resistant code. By understanding common types of exceptions, using try-except blocks effectively, and following best practices, you can create code that gracefully handles unexpected issues, making your applications more reliable and user-friendly.<\/p>\n\n\n\n<p>Whether you&#8217;re working on file operations, game development, or any other project, effective exception handling is a skill that will serve you well in your programming journey.<\/p>\n\n\n\n<p>I hope this guide gave you a solid understanding of key exception handling principles along with actionable coding examples. These learnings will help you eliminate crashes in your Python codebase and handle failures gracefully!<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p>Further Reading:<\/p>\n\n\n\n<p><a href=\"https:\/\/reviewnprep.com\/blog\/steps-to-improve-code-quality-as-a-developer\/\" target=\"_blank\" rel=\"noreferrer noopener\"><strong>Developers, you must follow these tips to improve code quality<\/strong>.<\/a><\/p>\n\n\n\n<p><strong><a href=\"https:\/\/reviewnprep.com\/blog\/data-engineer-vs-data-analyst-vs-data-scientist-salary-skills-background\/\" target=\"_blank\" rel=\"noreferrer noopener\">Start your career in data related field as a Data Engineer, Analyst or a Data Scientist.<\/a><\/strong><\/p>\n<\/blockquote>\n","protected":false},"excerpt":{"rendered":"<p>Learn how to effectively handle exceptions in Python with this comprehensive guide. Real-life examples and best practices will help you become a master in no time!<\/p>\n","protected":false},"author":1,"featured_media":4911,"comment_status":"open","ping_status":"open","sticky":true,"template":"","format":"standard","meta":{"footnotes":""},"categories":[253,254],"tags":[323,237],"class_list":["post-4908","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-development","category-python","tag-development","tag-python"],"_links":{"self":[{"href":"https:\/\/reviewnprep.com\/blog\/wp-json\/wp\/v2\/posts\/4908"}],"collection":[{"href":"https:\/\/reviewnprep.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/reviewnprep.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/reviewnprep.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/reviewnprep.com\/blog\/wp-json\/wp\/v2\/comments?post=4908"}],"version-history":[{"count":4,"href":"https:\/\/reviewnprep.com\/blog\/wp-json\/wp\/v2\/posts\/4908\/revisions"}],"predecessor-version":[{"id":4919,"href":"https:\/\/reviewnprep.com\/blog\/wp-json\/wp\/v2\/posts\/4908\/revisions\/4919"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/reviewnprep.com\/blog\/wp-json\/wp\/v2\/media\/4911"}],"wp:attachment":[{"href":"https:\/\/reviewnprep.com\/blog\/wp-json\/wp\/v2\/media?parent=4908"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/reviewnprep.com\/blog\/wp-json\/wp\/v2\/categories?post=4908"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/reviewnprep.com\/blog\/wp-json\/wp\/v2\/tags?post=4908"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}