{"id":923,"date":"2024-09-17T10:16:58","date_gmt":"2024-09-17T10:16:58","guid":{"rendered":"https:\/\/www.zframez.com\/articles\/?p=923"},"modified":"2024-10-16T16:02:58","modified_gmt":"2024-10-16T16:02:58","slug":"chapter-12-exception-handling-in-python-techniques-and-examples","status":"publish","type":"post","link":"https:\/\/www.zframez.com\/articles\/python-tutorials\/chapter-12-exception-handling-in-python-techniques-and-examples","title":{"rendered":"Chapter 12: Exception Handling in Python -Techniques and Examples"},"content":{"rendered":"<body>\n<div class=\"table-of-contents\" style=\"background-color: #066095; color: white; padding: 10px; border-radius: 10px; margin-top: 20px; display: flex; justify-content: space-between; align-items: center; font-weight: 600;\">\n  <span style=\"flex: 1; text-align: left;\">\n    <a href=\"https:\/\/www.zframez.com\/articles\/python-tutorials\/chapter-11-python-file-handling-reading-writing-and-managing-files\" style=\"color: white; text-decoration: underline;\">\u25c0 Previous<\/a>\n  <\/span>\n  \n  <span style=\"flex: 1; text-align: center;\">\n    <a href=\"https:\/\/www.zframez.com\/articles\/python-tutorials\" style=\"color: white; text-decoration: underline;\">Python Tutorials<\/a>\n  <\/span>\n  \n  <span style=\"flex: 1; text-align: right;\">\n    <span style=\"color: grey;\">Next \u25b6<\/span> <!-- No next link as it's the last chapter -->\n  <\/span>\n<\/div>\n\n\n\n\n<h1 class=\"wp-block-heading has-x-large-font-size\"><strong>Understanding Exception Handling in Python<\/strong><\/h1>\n\n\n\n<p><strong>What is an Exception?<\/strong><\/p>\n\n\n\n<p>Exceptions are errors that occur during the execution of your code. Before running a script, Python checks for syntax errors, but even if the syntax is correct, runtime errors, called exceptions, can still occur. In this chapter, we\u2019ll explore how exceptions work in Python and how you can handle them using <strong><code>try<\/code>, <code>except<\/code>, <code>else<\/code>, and <code>finally<\/code><\/strong> blocks. We\u2019ll also cover handling multiple exceptions, raising your own exceptions, and using the <code>assert<\/code> statement for validation. By the end of this chapter, you\u2019ll know how to handle errors gracefully in your programs and ensure they run smoothly even when something goes wrong.<\/p>\n\n\n\n<p>For example, in the code below, there are no syntax errors. However, during execution, the 2nd line \u201c<strong><code>c = a \/ <\/code>b<\/strong>\u201d will cause an exception because the value of the variable \u201cb\u201d is zero and dividing by zero is not allowed.<\/p>\n\n\n\n<pre class=\"wp-block-code has-background-color has-foreground-background-color has-text-color has-background has-link-color wp-elements-f92a3fe7f40c4bbfd9e18c5ec549ba1a\"><code>a, b = 10, 0\nc = a \/ b\n\n#Output:\nTraceback (most recent call last):\n  File \"except.py\", line 2, in &lt;module&gt;\n    c = a \/ b\n<strong>ZeroDivisionError:<\/strong> division by zero<\/code><\/pre>\n\n\n\n<p>Some other common exceptions are: <strong>ValueError, TypeError, NameError, SyntaxError, FileNotFound Error<\/strong> etc<\/p>\n\n\n\n<p><strong>ValueError :<\/strong> This exception is raised when a function gets a valid data type but an invalid value. For example, trying to convert a non-numeric string into an integer as show in below code:<\/p>\n\n\n\n<pre class=\"wp-block-code has-background-color has-foreground-background-color has-text-color has-background has-link-color wp-elements-8a29ccd04de334d52a483a5057561d5a\"><code>a = \"hi\"\nb = int(a)\n\n#Output:\nTraceback (most recent call last):\n  File \"except.py\", line 2, in &lt;module&gt;\n    b = int(a)\nValueError: invalid literal for int() with base 10: 'hi'<\/code><\/pre>\n\n\n\n<p><strong>TypeError<\/strong>: Raised when you perform an operation on a data type that doesn\u2019t support it. For example, trying to add a string and an integer together as shown below:<\/p>\n\n\n\n<pre class=\"wp-block-code has-background-color has-foreground-background-color has-text-color has-background has-link-color wp-elements-ec52ad45fab3cece4cbfa5f951219f12\"><code>a = \"hello\" + 5\n\n#Output :\nTraceback (most recent call last):\n  File \"except.py\", line 1, in &lt;module&gt;\n    a = \"hello\" + 5\nTypeError: can only concatenate str (not \"int\") to str<\/code><\/pre>\n\n\n\n<p><strong>NameError<\/strong>: Raised when a variable or function name is not found in the local or global namespace. For example, the following simple code uses a variable that hasn\u2019t been defined and will raise a NameError.<\/p>\n\n\n\n<pre class=\"wp-block-code has-background-color has-foreground-background-color has-text-color has-background has-link-color wp-elements-96d74cc60f0e8d8f279e98e945906c30\"><code>a = hello\n\n#Output: \nTraceback (most recent call last):\n  File \"except.py\", line 1, in &lt;module&gt;\n    a = hello\nNameError: name 'hello' is not defined<\/code><\/pre>\n\n\n\n<p><strong> FileNotFoundError:<\/strong> Raised when attempting to open a file that does not exist. For example, the following code uses the <code>open<\/code> function to open the file <code>abcd.txt<\/code> in read-only mode and will raise a FileNotFoundError if the file does not exist in the same folder as the script.<\/p>\n\n\n\n<pre class=\"wp-block-code has-background-color has-foreground-background-color has-text-color has-background has-link-color wp-elements-a69e29d185caa131b9fdd600e4436823\"><code>file_id = open (\"abcd.txt\" , r) \n\n#Output:\nTraceback (most recent call last):\n  File \"except.py\", line 1, in &lt;module&gt;\n    fid = open(\"abcd.txt\", 'r')\nFileNotFoundError: [Errno 2] No such file or directory: 'abcd.txt'<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading has-large-font-size\"><strong>What is Exception Handling?<\/strong><\/h2>\n\n\n\n<p>Exception handling is the technique of catching errors to prevent the unexpected termination of a script. If you suspect a part of your code may raise an error, you can use the <strong>try-except<\/strong> block to handle that exception.<\/p>\n\n\n\n<p>For example, to handle the <code>FileNotFoundError<\/code> in the code above:<\/p>\n\n\n\n<pre class=\"wp-block-code has-background-color has-foreground-background-color has-text-color has-background has-link-color wp-elements-be9a57287f347a0914f65291a814893c\"><code>try:\n    fid = open(\"abcd.txt\", 'r')\nexcept FileNotFoundError:\n    print(\"File is not present, skipping the reading process...\")\nelse:\n    print(fid.read())\n    fid.close()<\/code><\/pre>\n\n\n\n<p>In this code:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The <code>try<\/code> block contains the code that might raise an exception.<\/li>\n\n\n\n<li>If a <code>FileNotFoundError<\/code> occurs, the <code>except<\/code> block will be executed.<\/li>\n\n\n\n<li>If no error occurs, the <code>else<\/code> block is executed.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading has-large-font-size\"><strong>Handling Multiple Exceptions<\/strong><\/h2>\n\n\n\n<p>You can catch multiple exceptions by using either a tuple of exceptions or multiple <code>except<\/code> clauses.<\/p>\n\n\n\n<p><strong>Using a Tuple of Exceptions:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-background-color has-foreground-background-color has-text-color has-background has-link-color wp-elements-e2675122350c97bacab7edc42f61b42a\"><code>try:\n    fid = open(\"abcd.txt\", 'r')\n    fid.write(\"hello world\")\nexcept (FileNotFoundError, IOError):\n    print(\"Error in opening file or writing ...\")\nelse:\n    fid.close()<\/code><\/pre>\n\n\n\n<p><strong>Using Multiple <code>except<\/code> Clauses:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-background-color has-foreground-background-color has-text-color has-background has-link-color wp-elements-e0cd761333c726bf3134356d55eed9c6\"><code>try:\n    fid = open(\"abcd.txt\", 'r')\n    fid.write(\"hello world\")\nexcept FileNotFoundError:\n    print(\"Error in opening file\")\nexcept IOError:\n    print(\"File opened successfully, but couldn't write\")\nelse:\n    fid.close()<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading has-large-font-size\"><strong>Using \u201c<code>finally<\/code>\u201d in Exception Handling<\/strong> : <\/h2>\n\n\n\n<p>The \u201c<code>finally\"<\/code> block is used to execute code regardless of whether an exception is raised. It is typically used to release resources like closing files or network connections. In the following example, the <strong>\u201c<code>finally<\/code>\u201c<\/strong> block will always run, whether or not an exception is raised.<\/p>\n\n\n\n<pre class=\"wp-block-code has-background-color has-foreground-background-color has-text-color has-background has-link-color wp-elements-a731fe7fa526825cb3f029a17f81e250\"><code>fid = open(\"abcd.txt\", 'r')\n\ntry:\n    fid.write(\"hello world\")\nexcept IOError:\n    print(\"Write operation: Failed\")\nelse:\n    print(\"Write operation: Successful\")\nfinally:\n    print(\"Inside finally...\")\n    fid.close()<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading has-large-font-size\"><strong>User-Defined Exceptions<\/strong><\/h2>\n\n\n\n<p>You can create custom exceptions by defining a new class that inherits from the built-in \u201c<code><strong>Exception<\/strong><\/code>\u201d class.  You can use this custom exception with the \u201c<strong><code>raise<\/code>\u201d <\/strong>keyword to trigger the exception manually. For example, the following code will print a range of numbers if the user input is a number greater than 0 ,  but will exit the code raising the MyInputError defined by the user if the user\u2019s input is less than 0.<\/p>\n\n\n\n<p><strong>Raising a Custom Exception:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-background-color has-foreground-background-color has-text-color has-background has-link-color wp-elements-834be082f391d84c77042201d381bd6e\"><code>class MyInputError(Exception):\n    pass\n\na = int(input(\"Enter a number: \"))\n\ntry:\n    if a &lt;= 0:\n        raise MyInputError()\nexcept MyInputError:\n    print(\"Enter a number greater than 0\")\nelse:\n    for tmp in range(a):\n        print(tmp)<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading has-large-font-size\"><strong>Exception Arguments<\/strong><\/h2>\n\n\n\n<p>When raising an exception, you can pass arguments to it, which can be used later in the <code>except<\/code> block or displayed if not caught.<\/p>\n\n\n\n<pre class=\"wp-block-code has-background-color has-foreground-background-color has-text-color has-background has-link-color wp-elements-be93a5c5b198f98ccc28e8ad6bc3a1b4\"><code>a = int(input(\"Enter a number: \"))\n\nclass MyInputError(Exception):\n    pass\n\ntry:\n    if a &lt; 0:\n        raise MyInputError(\"Input is less than 0\")\n    if a &lt; 5:\n        raise MyInputError(\"Input is less than 5\")\nexcept MyInputError as tmp:\n    print(tmp)\nelse:\n    for tmp in range(a):\n        print(tmp)\n\n#Output :\nEnter a number: 3\nInput is less than 5<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading has-large-font-size\"><strong>Python\u2019s \u201c<code>assert<\/code>\u201d Statement<\/strong><\/h2>\n\n\n\n<p>The \u201c<code><strong>assert<\/strong>\"<\/code> statement is used to verify that a condition holds true. If the condition is false, an <code><strong>AssertionError<\/strong><\/code> is raised.<\/p>\n\n\n\n<pre class=\"wp-block-code has-background-color has-foreground-background-color has-text-color has-background has-link-color wp-elements-52bd5f6dbeb0cf73fba6f9def770a9c4\"><code>a = int(input(\"Enter a number: \"))\nassert a &gt; 0, \"Wrong Input\"\n\nfor tmp in range(a):\n    print(tmp)\n\n#Output (If the input is less than or equal to zero)\nTraceback (most recent call last):\n  File \"except.py\", line 2, in &lt;module&gt;\n    assert a &gt; 0, \"Wrong Input\"\nAssertionError: Wrong Input<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity is-style-wide\">\n\n\n\n<div class=\"table-of-contents\" style=\"background-color: #066095; color: white; padding: 10px; border-radius: 10px; margin-top: 20px; display: flex; justify-content: space-between; align-items: center; font-weight: 600;\">\n  <span style=\"flex: 1; text-align: left;\">\n    <a href=\"https:\/\/www.zframez.com\/articles\/python-tutorials\/chapter-11-python-file-handling-reading-writing-and-managing-files\" style=\"color: white; text-decoration: underline;\">\u25c0 Previous<\/a>\n  <\/span>\n  \n  <span style=\"flex: 1; text-align: center;\">\n    <a href=\"https:\/\/www.zframez.com\/articles\/python-tutorials\" style=\"color: white; text-decoration: underline;\">Python Tutorials<\/a>\n  <\/span>\n  \n  <span style=\"flex: 1; text-align: right;\">\n    <span style=\"color: grey;\">Next \u25b6<\/span> <!-- No next link as it's the last chapter -->\n  <\/span>\n<\/div>\n\n<\/body>","protected":false},"excerpt":{"rendered":"<p>\u25c0 Previous Python Tutorials Next \u25b6 Understanding Exception Handling in Python What is an Exception? Exceptions are errors that occur during the execution of your code. Before running a script, Python checks for syntax errors, but even if the syntax is correct, runtime errors, called exceptions, can still occur. In this chapter, we\u2019ll explore how [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"wp-custom-template-post-with-sidebar2","format":"standard","meta":{"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[46],"tags":[322,329,324,326,280,327,325,328,323],"class_list":["post-923","post","type-post","status-publish","format-standard","hentry","category-python-tutorials","tag-custom-exceptions","tag-filenotfounderror","tag-handling-exceptions-in-python","tag-python-exceptions","tag-python-tutorials","tag-raising-exceptions-in-python","tag-try-except-block","tag-typeerror","tag-valueerror"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.4 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Chapter 12: Exception Handling in Python -Techniques and Examples - Tutorials<\/title>\n<meta name=\"description\" content=\"Learn how to handle exceptions in Python using try-except blocks, handle multiple exceptions, create user-defined exceptions, and understand key errors like ValueError, TypeError, and FileNotFoundError\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.zframez.com\/articles\/python-tutorials\/chapter-12-exception-handling-in-python-techniques-and-examples\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Chapter 12: Exception Handling in Python - Try-Except, Custom Exceptions, and Error Types\" \/>\n<meta property=\"og:description\" content=\"Master Python&#039;s exception handling techniques, including try-except blocks, handling multiple exceptions, raising custom exceptions, and understanding common errors like ValueError, TypeError, and FileNotFoundError\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.zframez.com\/articles\/python-tutorials\/chapter-12-exception-handling-in-python-techniques-and-examples\" \/>\n<meta property=\"og:site_name\" content=\"Tutorials\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/zframez\/\" \/>\n<meta property=\"article:published_time\" content=\"2024-09-17T10:16:58+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-10-16T16:02:58+00:00\" \/>\n<meta name=\"author\" content=\"sajith achipra\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@zframez\" \/>\n<meta name=\"twitter:site\" content=\"@zframez\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"sajith achipra\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"3 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/www.zframez.com\\\/articles\\\/python-tutorials\\\/chapter-12-exception-handling-in-python-techniques-and-examples#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.zframez.com\\\/articles\\\/python-tutorials\\\/chapter-12-exception-handling-in-python-techniques-and-examples\"},\"author\":{\"name\":\"sajith achipra\",\"@id\":\"https:\\\/\\\/www.zframez.com\\\/articles\\\/#\\\/schema\\\/person\\\/8b3b88007644501771d2452d3cc80f41\"},\"headline\":\"Chapter 12: Exception Handling in Python -Techniques and Examples\",\"datePublished\":\"2024-09-17T10:16:58+00:00\",\"dateModified\":\"2024-10-16T16:02:58+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/www.zframez.com\\\/articles\\\/python-tutorials\\\/chapter-12-exception-handling-in-python-techniques-and-examples\"},\"wordCount\":593,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\\\/\\\/www.zframez.com\\\/articles\\\/#organization\"},\"keywords\":[\"custom exceptions\",\"FileNotFoundError\",\"handling exceptions in Python\",\"Python exceptions\",\"Python tutorials\",\"raising exceptions in Python\",\"try-except block\",\"TypeError\",\"ValueError\"],\"articleSection\":[\"python tutorials\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\\\/\\\/www.zframez.com\\\/articles\\\/python-tutorials\\\/chapter-12-exception-handling-in-python-techniques-and-examples#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/www.zframez.com\\\/articles\\\/python-tutorials\\\/chapter-12-exception-handling-in-python-techniques-and-examples\",\"url\":\"https:\\\/\\\/www.zframez.com\\\/articles\\\/python-tutorials\\\/chapter-12-exception-handling-in-python-techniques-and-examples\",\"name\":\"Chapter 12: Exception Handling in Python -Techniques and Examples - Tutorials\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.zframez.com\\\/articles\\\/#website\"},\"datePublished\":\"2024-09-17T10:16:58+00:00\",\"dateModified\":\"2024-10-16T16:02:58+00:00\",\"description\":\"Learn how to handle exceptions in Python using try-except blocks, handle multiple exceptions, create user-defined exceptions, and understand key errors like ValueError, TypeError, and FileNotFoundError\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/www.zframez.com\\\/articles\\\/python-tutorials\\\/chapter-12-exception-handling-in-python-techniques-and-examples#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/www.zframez.com\\\/articles\\\/python-tutorials\\\/chapter-12-exception-handling-in-python-techniques-and-examples\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/www.zframez.com\\\/articles\\\/python-tutorials\\\/chapter-12-exception-handling-in-python-techniques-and-examples#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Tutorials\",\"item\":\"https:\\\/\\\/www.zframez.com\\\/articles\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Chapter 12: Exception Handling in Python -Techniques and Examples\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/www.zframez.com\\\/articles\\\/#website\",\"url\":\"https:\\\/\\\/www.zframez.com\\\/articles\\\/\",\"name\":\"zframez tutorials\",\"description\":\"Learn networking bit by bit\",\"publisher\":{\"@id\":\"https:\\\/\\\/www.zframez.com\\\/articles\\\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/www.zframez.com\\\/articles\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\\\/\\\/www.zframez.com\\\/articles\\\/#organization\",\"name\":\"zframez technologies\",\"url\":\"https:\\\/\\\/www.zframez.com\\\/articles\\\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.zframez.com\\\/articles\\\/#\\\/schema\\\/logo\\\/image\\\/\",\"url\":\"https:\\\/\\\/i0.wp.com\\\/www.zframez.com\\\/articles\\\/wp-content\\\/uploads\\\/2024\\\/07\\\/zframez-logo.jpg?fit=864%2C864&ssl=1\",\"contentUrl\":\"https:\\\/\\\/i0.wp.com\\\/www.zframez.com\\\/articles\\\/wp-content\\\/uploads\\\/2024\\\/07\\\/zframez-logo.jpg?fit=864%2C864&ssl=1\",\"width\":864,\"height\":864,\"caption\":\"zframez technologies\"},\"image\":{\"@id\":\"https:\\\/\\\/www.zframez.com\\\/articles\\\/#\\\/schema\\\/logo\\\/image\\\/\"},\"sameAs\":[\"https:\\\/\\\/www.facebook.com\\\/zframez\\\/\",\"https:\\\/\\\/x.com\\\/zframez\",\"https:\\\/\\\/www.instagram.com\\\/zframez_technologies\\\/\"]},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/www.zframez.com\\\/articles\\\/#\\\/schema\\\/person\\\/8b3b88007644501771d2452d3cc80f41\",\"name\":\"sajith achipra\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/3d9f27c5311500982b6f19d03d0506f1c328f30f51d8d5f73f46577687fd81f8?s=96&d=mm&r=g\",\"url\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/3d9f27c5311500982b6f19d03d0506f1c328f30f51d8d5f73f46577687fd81f8?s=96&d=mm&r=g\",\"contentUrl\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/3d9f27c5311500982b6f19d03d0506f1c328f30f51d8d5f73f46577687fd81f8?s=96&d=mm&r=g\",\"caption\":\"sajith achipra\"},\"sameAs\":[\"http:\\\/\\\/www.zframez.com\"]}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Chapter 12: Exception Handling in Python -Techniques and Examples - Tutorials","description":"Learn how to handle exceptions in Python using try-except blocks, handle multiple exceptions, create user-defined exceptions, and understand key errors like ValueError, TypeError, and FileNotFoundError","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:\/\/www.zframez.com\/articles\/python-tutorials\/chapter-12-exception-handling-in-python-techniques-and-examples","og_locale":"en_US","og_type":"article","og_title":"Chapter 12: Exception Handling in Python - Try-Except, Custom Exceptions, and Error Types","og_description":"Master Python's exception handling techniques, including try-except blocks, handling multiple exceptions, raising custom exceptions, and understanding common errors like ValueError, TypeError, and FileNotFoundError","og_url":"https:\/\/www.zframez.com\/articles\/python-tutorials\/chapter-12-exception-handling-in-python-techniques-and-examples","og_site_name":"Tutorials","article_publisher":"https:\/\/www.facebook.com\/zframez\/","article_published_time":"2024-09-17T10:16:58+00:00","article_modified_time":"2024-10-16T16:02:58+00:00","author":"sajith achipra","twitter_card":"summary_large_image","twitter_creator":"@zframez","twitter_site":"@zframez","twitter_misc":{"Written by":"sajith achipra","Est. reading time":"3 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.zframez.com\/articles\/python-tutorials\/chapter-12-exception-handling-in-python-techniques-and-examples#article","isPartOf":{"@id":"https:\/\/www.zframez.com\/articles\/python-tutorials\/chapter-12-exception-handling-in-python-techniques-and-examples"},"author":{"name":"sajith achipra","@id":"https:\/\/www.zframez.com\/articles\/#\/schema\/person\/8b3b88007644501771d2452d3cc80f41"},"headline":"Chapter 12: Exception Handling in Python -Techniques and Examples","datePublished":"2024-09-17T10:16:58+00:00","dateModified":"2024-10-16T16:02:58+00:00","mainEntityOfPage":{"@id":"https:\/\/www.zframez.com\/articles\/python-tutorials\/chapter-12-exception-handling-in-python-techniques-and-examples"},"wordCount":593,"commentCount":0,"publisher":{"@id":"https:\/\/www.zframez.com\/articles\/#organization"},"keywords":["custom exceptions","FileNotFoundError","handling exceptions in Python","Python exceptions","Python tutorials","raising exceptions in Python","try-except block","TypeError","ValueError"],"articleSection":["python tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.zframez.com\/articles\/python-tutorials\/chapter-12-exception-handling-in-python-techniques-and-examples#respond"]}]},{"@type":"WebPage","@id":"https:\/\/www.zframez.com\/articles\/python-tutorials\/chapter-12-exception-handling-in-python-techniques-and-examples","url":"https:\/\/www.zframez.com\/articles\/python-tutorials\/chapter-12-exception-handling-in-python-techniques-and-examples","name":"Chapter 12: Exception Handling in Python -Techniques and Examples - Tutorials","isPartOf":{"@id":"https:\/\/www.zframez.com\/articles\/#website"},"datePublished":"2024-09-17T10:16:58+00:00","dateModified":"2024-10-16T16:02:58+00:00","description":"Learn how to handle exceptions in Python using try-except blocks, handle multiple exceptions, create user-defined exceptions, and understand key errors like ValueError, TypeError, and FileNotFoundError","breadcrumb":{"@id":"https:\/\/www.zframez.com\/articles\/python-tutorials\/chapter-12-exception-handling-in-python-techniques-and-examples#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.zframez.com\/articles\/python-tutorials\/chapter-12-exception-handling-in-python-techniques-and-examples"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/www.zframez.com\/articles\/python-tutorials\/chapter-12-exception-handling-in-python-techniques-and-examples#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Tutorials","item":"https:\/\/www.zframez.com\/articles"},{"@type":"ListItem","position":2,"name":"Chapter 12: Exception Handling in Python -Techniques and Examples"}]},{"@type":"WebSite","@id":"https:\/\/www.zframez.com\/articles\/#website","url":"https:\/\/www.zframez.com\/articles\/","name":"zframez tutorials","description":"Learn networking bit by bit","publisher":{"@id":"https:\/\/www.zframez.com\/articles\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.zframez.com\/articles\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/www.zframez.com\/articles\/#organization","name":"zframez technologies","url":"https:\/\/www.zframez.com\/articles\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.zframez.com\/articles\/#\/schema\/logo\/image\/","url":"https:\/\/i0.wp.com\/www.zframez.com\/articles\/wp-content\/uploads\/2024\/07\/zframez-logo.jpg?fit=864%2C864&ssl=1","contentUrl":"https:\/\/i0.wp.com\/www.zframez.com\/articles\/wp-content\/uploads\/2024\/07\/zframez-logo.jpg?fit=864%2C864&ssl=1","width":864,"height":864,"caption":"zframez technologies"},"image":{"@id":"https:\/\/www.zframez.com\/articles\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/zframez\/","https:\/\/x.com\/zframez","https:\/\/www.instagram.com\/zframez_technologies\/"]},{"@type":"Person","@id":"https:\/\/www.zframez.com\/articles\/#\/schema\/person\/8b3b88007644501771d2452d3cc80f41","name":"sajith achipra","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/3d9f27c5311500982b6f19d03d0506f1c328f30f51d8d5f73f46577687fd81f8?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/3d9f27c5311500982b6f19d03d0506f1c328f30f51d8d5f73f46577687fd81f8?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/3d9f27c5311500982b6f19d03d0506f1c328f30f51d8d5f73f46577687fd81f8?s=96&d=mm&r=g","caption":"sajith achipra"},"sameAs":["http:\/\/www.zframez.com"]}]}},"jetpack_featured_media_url":"","jetpack-related-posts":[{"id":83,"url":"https:\/\/www.zframez.com\/articles\/python-tutorials\/chapter-1-introduction-to-python-programming","url_meta":{"origin":923,"position":0},"title":"Chapter 1: Introduction to Python Programming","author":"sajith achipra","date":"September 4, 2024","format":false,"excerpt":"\u25c0 Previous Python Tutorials Next \u25b6 In this Python tutorial, we'll explore Python's origins, key milestones, and its standout features and benefits. Whether you're new to programming or looking to expand your skills, this guide will provide you with a solid foundation in Python. If you want to understand why\u2026","rel":"","context":"In &quot;python tutorials&quot;","block_context":{"text":"python tutorials","link":"https:\/\/www.zframez.com\/articles\/category\/python-tutorials"},"img":{"alt_text":"Table filled with Python-related materials, including a computer displaying Python code, a Python textbook, and notes about Python","src":"https:\/\/i0.wp.com\/www.zframez.com\/articles\/wp-content\/uploads\/2024\/09\/working-with-python.webp?fit=1024%2C1024&ssl=1&resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/www.zframez.com\/articles\/wp-content\/uploads\/2024\/09\/working-with-python.webp?fit=1024%2C1024&ssl=1&resize=350%2C200 1x, https:\/\/i0.wp.com\/www.zframez.com\/articles\/wp-content\/uploads\/2024\/09\/working-with-python.webp?fit=1024%2C1024&ssl=1&resize=525%2C300 1.5x, https:\/\/i0.wp.com\/www.zframez.com\/articles\/wp-content\/uploads\/2024\/09\/working-with-python.webp?fit=1024%2C1024&ssl=1&resize=700%2C400 2x"},"classes":[]},{"id":901,"url":"https:\/\/www.zframez.com\/articles\/python-tutorials\/chapter-6-python-while-and-for-loops-examples-and-explanations","url_meta":{"origin":923,"position":1},"title":"Chapter 6: Python While and For Loops: Examples and Explanations","author":"sajith achipra","date":"September 15, 2024","format":false,"excerpt":"\u25c0 Previous Python Tutorials Next \u25b6 Python While and For Loops In this chapter of our Python tutorial series, we will explore two essential looping structures in Python: while loops and for loops. Loops are a fundamental part of programming, allowing you to execute a block of code repeatedly under\u2026","rel":"","context":"In &quot;python tutorials&quot;","block_context":{"text":"python tutorials","link":"https:\/\/www.zframez.com\/articles\/category\/python-tutorials"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":917,"url":"https:\/\/www.zframez.com\/articles\/python-tutorials\/chapter-11-python-file-handling-reading-writing-and-managing-files","url_meta":{"origin":923,"position":2},"title":"Chapter 11: Python File Handling -Reading, Writing, and Managing Files","author":"sajith achipra","date":"September 15, 2024","format":false,"excerpt":"\u25c0 Previous Python Tutorials Next \u25b6 Working with File Operations in Python In this chapter, we\u2019ll explore how to work with files in Python, including reading, writing, and managing files efficiently. Files are often used to store inputs or outputs during script execution, and Python\u2019s built-in support for file handling\u2026","rel":"","context":"In &quot;python tutorials&quot;","block_context":{"text":"python tutorials","link":"https:\/\/www.zframez.com\/articles\/category\/python-tutorials"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":904,"url":"https:\/\/www.zframez.com\/articles\/python-tutorials\/chapter-7-working-with-strings-in-python","url_meta":{"origin":923,"position":3},"title":"Chapter 7: Working with Strings in Python","author":"sajith achipra","date":"September 15, 2024","format":false,"excerpt":"\u25c0 Previous Python Tutorials Next \u25b6 Python String Manipulation: Methods and Examples In Chapter 7, we\u2019ll be looking at how to work with strings in Python. Strings are used everywhere in programming, and Python provides a lot of methods to make string manipulation easy. In this chapter, we\u2019ll explore methods\u2026","rel":"","context":"In &quot;python tutorials&quot;","block_context":{"text":"python tutorials","link":"https:\/\/www.zframez.com\/articles\/category\/python-tutorials"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":90,"url":"https:\/\/www.zframez.com\/articles\/python-tutorials\/chapter-2-setting-up-python","url_meta":{"origin":923,"position":4},"title":"Chapter 2: Setting Up Python","author":"sajith achipra","date":"September 4, 2024","format":false,"excerpt":"\u25c0 Previous Python Tutorials Next \u25b6 Before you can start writing and running Python code, you\u2019ll need to set up Python on your computer. In this chapter, we\u2019ll guide you through the process of installing Python on Windows, macOS, and Linux. We\u2019ll also explain what an Integrated Development Environment (IDE)\u2026","rel":"","context":"In &quot;python tutorials&quot;","block_context":{"text":"python tutorials","link":"https:\/\/www.zframez.com\/articles\/category\/python-tutorials"},"img":{"alt_text":"Screenshot of the official Python download page, highlighting the process of setting up Python.","src":"https:\/\/i0.wp.com\/www.zframez.com\/articles\/wp-content\/uploads\/2024\/09\/download-and-install-python.png?fit=1200%2C499&ssl=1&resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/www.zframez.com\/articles\/wp-content\/uploads\/2024\/09\/download-and-install-python.png?fit=1200%2C499&ssl=1&resize=350%2C200 1x, https:\/\/i0.wp.com\/www.zframez.com\/articles\/wp-content\/uploads\/2024\/09\/download-and-install-python.png?fit=1200%2C499&ssl=1&resize=525%2C300 1.5x, https:\/\/i0.wp.com\/www.zframez.com\/articles\/wp-content\/uploads\/2024\/09\/download-and-install-python.png?fit=1200%2C499&ssl=1&resize=700%2C400 2x, https:\/\/i0.wp.com\/www.zframez.com\/articles\/wp-content\/uploads\/2024\/09\/download-and-install-python.png?fit=1200%2C499&ssl=1&resize=1050%2C600 3x"},"classes":[]},{"id":98,"url":"https:\/\/www.zframez.com\/articles\/python-tutorials\/chapter-3-working-with-variables-in-python","url_meta":{"origin":923,"position":5},"title":"Chapter 3: Working with Variables in Python","author":"sajith achipra","date":"September 4, 2024","format":false,"excerpt":"\u25c0 Previous Python Tutorials Next \u25b6 In Python, variables are one of the fundamental concepts you'll work with. They allow you to store data that your programs can manipulate and use. In this chapter, we\u2019ll explore what variables are, how to check the Python version you\u2019re using, and the different\u2026","rel":"","context":"In &quot;python tutorials&quot;","block_context":{"text":"python tutorials","link":"https:\/\/www.zframez.com\/articles\/category\/python-tutorials"},"img":{"alt_text":"Computer displaying a program, with a book and pen on the table, representing learning and coding in Python.","src":"https:\/\/i0.wp.com\/www.zframez.com\/articles\/wp-content\/uploads\/2024\/09\/Understanding-Python-variables.jpg?fit=684%2C457&ssl=1&resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/www.zframez.com\/articles\/wp-content\/uploads\/2024\/09\/Understanding-Python-variables.jpg?fit=684%2C457&ssl=1&resize=350%2C200 1x, https:\/\/i0.wp.com\/www.zframez.com\/articles\/wp-content\/uploads\/2024\/09\/Understanding-Python-variables.jpg?fit=684%2C457&ssl=1&resize=525%2C300 1.5x"},"classes":[]}],"jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/www.zframez.com\/articles\/wp-json\/wp\/v2\/posts\/923","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.zframez.com\/articles\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.zframez.com\/articles\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.zframez.com\/articles\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/www.zframez.com\/articles\/wp-json\/wp\/v2\/comments?post=923"}],"version-history":[{"count":5,"href":"https:\/\/www.zframez.com\/articles\/wp-json\/wp\/v2\/posts\/923\/revisions"}],"predecessor-version":[{"id":1089,"href":"https:\/\/www.zframez.com\/articles\/wp-json\/wp\/v2\/posts\/923\/revisions\/1089"}],"wp:attachment":[{"href":"https:\/\/www.zframez.com\/articles\/wp-json\/wp\/v2\/media?parent=923"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.zframez.com\/articles\/wp-json\/wp\/v2\/categories?post=923"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.zframez.com\/articles\/wp-json\/wp\/v2\/tags?post=923"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}