{"id":4204,"date":"2023-09-19T21:28:18","date_gmt":"2023-09-19T15:58:18","guid":{"rendered":"https:\/\/cbsepython.in\/?p=4204"},"modified":"2023-09-20T22:22:23","modified_gmt":"2023-09-20T16:52:23","slug":"exception-handling-in-python-class-12-notes","status":"publish","type":"post","link":"https:\/\/cbsepython.in\/exception-handling-in-python-class-12-notes\/","title":{"rendered":"Exception Handling in Python Class 12 Notes"},"content":{"rendered":"<h2><span style=\"color: #000000;\">Exception Handling in Python<\/span><\/h2>\n<p><span style=\"color: #000000;\">Here students of class 12 will learn about the \u00a0Exception Handling in Python. These notes are made to help the students in their board preparation. The topic \u00a0Exception Handling is introduced by the CBSE for the session 2023-24 onward.\u00a0<\/span><\/p>\n<h3><span style=\"color: #000000;\">Errors<\/span><\/h3>\n<p><span style=\"color: #000000;\">Errors in a program can be categorized into following types:<\/span><\/p>\n<p><span style=\"color: #000000;\"><strong>1. Compile Time Error:<\/strong> Errors that occur during the compilation of the program.<\/span><\/p>\n<p><span style=\"color: #000000;\"><strong>2. Run Time Error:<\/strong> Errors that occur while the program is running. Some of the example of run time error are:<\/span><\/p>\n<ul>\n<li><span style=\"color: #000000;\">Division by Zero<\/span><\/li>\n<li><span style=\"color: #000000;\">Using of undefined variable<\/span><\/li>\n<li><span style=\"color: #000000;\">Trying to access a non existing file<\/span><\/li>\n<\/ul>\n<p><span style=\"color: #000000;\"><strong>3. Logical Error:<\/strong> Errors in the program&#8217;s logic, which do not produce errors but lead to incorrect results. Some of the example of logical error are:<\/span><\/p>\n<ul>\n<li><span style=\"color: #000000;\">Giving wrong operator precedence<\/span><\/li>\n<li><span style=\"color: #000000;\">using wrong variable name for calculation<\/span><\/li>\n<\/ul>\n<p>&nbsp;<\/p>\n<p><span style=\"color: #000000;\"><strong>4. Syntax Errors:<\/strong> Mistakes in writing code that prevent the program from running. Some of the example of syntax error are:<\/span><\/p>\n<ul>\n<li><span style=\"color: #000000;\">Incorrect Indentation<\/span><\/li>\n<li><span style=\"color: #000000;\">Misspelled a keyword<\/span><\/li>\n<li><span style=\"color: #000000;\">leaving out a symbol such as colon (:), parentheses [{()}] or comma (,).<\/span><\/li>\n<\/ul>\n<p><span style=\"color: #000000;\"><strong>5. Semantics Errors:<\/strong> Logic errors that produce unintended results.<\/span><\/p>\n<p>&nbsp;<\/p>\n<p style=\"text-align: center;\"><span style=\"text-decoration: underline;\"><span style=\"color: #000000; text-decoration: underline;\">Exception Handling in Python<\/span><\/span><\/p>\n<h2><span style=\"color: #000000;\">\u00a0Exception<\/span><\/h2>\n<p><span style=\"color: #000000;\">&#8211; An exception is a type of error that occurs during program execution.<\/span><\/p>\n<p><span style=\"color: #000000;\">&#8211; Python generates an exception whenever an error is encountered.<\/span><\/p>\n<p><span style=\"color: #000000;\">&#8211; Exceptions can be handled to prevent the program from crashing.<\/span><\/p>\n<p>&nbsp;<\/p>\n<h3><span style=\"color: #000000;\">\u00a0Error vs. Exception<\/span><\/h3>\n<p><span style=\"color: #000000;\">&#8211; Error: Any mistake or issue in the code.<\/span><\/p>\n<p><span style=\"color: #000000;\">&#8211; Exception: An unexpected situation or error during program execution.<\/span><\/p>\n<p>&nbsp;<\/p>\n<h2><span style=\"color: #000000;\">\u00a0Exception Handling<\/span><\/h2>\n<p><span style=\"color: #000000;\">&#8211; Exception handling is the process of dealing with run-time errors.<\/span><\/p>\n<p><span style=\"color: #000000;\">&#8211; It involves using `try&#8230;except` blocks to catch and handle exceptions.<\/span><\/p>\n<p>&nbsp;<\/p>\n<h2><span style=\"color: #000000;\">Program without Exception Handling<\/span><\/h2>\n<p><span style=\"color: #000000;\">Python Program to divide two numbers without exception handling<\/span><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">num1 = int(input(\"Enter first number\"))\r\n\r\nnum2 = int(input(\"Enter Second number\"))\r\n\r\nresult = num1 \/ num2\r\n\r\nprint(\"Result:\", result)\r\n<\/pre>\n<p>&nbsp;<\/p>\n<p>Output:<\/p>\n<p><img fetchpriority=\"high\" decoding=\"async\" class=\"alignnone wp-image-4220 size-full\" src=\"https:\/\/cbsepython.in\/wp-content\/uploads\/2023\/09\/Python-Exception-Handling-.jpg\" alt=\"Exception Handling in Python Class 12 Notes\" width=\"548\" height=\"121\" title=\"\" srcset=\"https:\/\/cbsepython.in\/wp-content\/uploads\/2023\/09\/Python-Exception-Handling-.jpg 548w, https:\/\/cbsepython.in\/wp-content\/uploads\/2023\/09\/Python-Exception-Handling--300x66.jpg 300w\" sizes=\"(max-width: 548px) 100vw, 548px\" \/><\/p>\n<p><img decoding=\"async\" class=\"alignnone wp-image-4218 size-full\" src=\"https:\/\/cbsepython.in\/wp-content\/uploads\/2023\/09\/Exception-in-Python.jpg\" alt=\"Exception Handling in Python Class 12 Notes\" width=\"1054\" height=\"249\" title=\"\" srcset=\"https:\/\/cbsepython.in\/wp-content\/uploads\/2023\/09\/Exception-in-Python.jpg 1054w, https:\/\/cbsepython.in\/wp-content\/uploads\/2023\/09\/Exception-in-Python-300x71.jpg 300w, https:\/\/cbsepython.in\/wp-content\/uploads\/2023\/09\/Exception-in-Python-1024x242.jpg 1024w, https:\/\/cbsepython.in\/wp-content\/uploads\/2023\/09\/Exception-in-Python-768x181.jpg 768w\" sizes=\"(max-width: 1054px) 100vw, 1054px\" \/><\/p>\n<p>&nbsp;<\/p>\n<h2><span style=\"color: #000000;\">Program with Exception Handling<\/span><\/h2>\n<p><span style=\"color: #000000;\">Python Program to divide two numbers with exception handling<\/span><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">num1 = int(input(\"Enter first number\"))\r\n\r\nnum2 = int(input(\"Enter Second number\"))\r\n\r\ntry:\r\n    result = num1 \/ num2\r\n\r\n    print(\"Result:\", result)\r\n\r\n\r\nexcept ZeroDivisionError:\r\n\r\n    print (\"You Can not divide a number by Zero....\")\r\n<\/pre>\n<p>&nbsp;<\/p>\n<p><img decoding=\"async\" class=\"alignnone wp-image-4217 size-full\" src=\"https:\/\/cbsepython.in\/wp-content\/uploads\/2023\/09\/Exception-handing-in-Python.jpg\" alt=\"Exception Handling in Python Class 12 Notes\" width=\"662\" height=\"140\" title=\"\" srcset=\"https:\/\/cbsepython.in\/wp-content\/uploads\/2023\/09\/Exception-handing-in-Python.jpg 662w, https:\/\/cbsepython.in\/wp-content\/uploads\/2023\/09\/Exception-handing-in-Python-300x63.jpg 300w\" sizes=\"(max-width: 662px) 100vw, 662px\" \/><\/p>\n<p style=\"text-align: center;\"><span style=\"text-decoration: underline; color: #000000;\">Exception Handling in Python<\/span><\/p>\n<h3><span style=\"color: #000000;\">\u00a0Built-in Exceptions in Python<\/span><\/h3>\n<p><span style=\"color: #000000;\">&#8211; Python provides various built-in exceptions that can be caught and handled using `try&#8230;except`.<\/span><\/p>\n<p>&nbsp;<\/p>\n<p><span style=\"color: #000000;\">In Python, exceptions are a way to handle runtime errors and exceptional situations that can occur during program execution. Python provides a variety of built-in exceptions that you can use to catch and handle different types of errors. Here are some of the most commonly used built-in exceptions in Python:<\/span><\/p>\n<p><span style=\"color: #000000;\"><strong>1. `SyntaxError`:<\/strong> Raised when there is a syntax error in your code.<\/span><\/p>\n<p><span style=\"color: #000000;\"><strong>2. `IndentationError`:<\/strong> Raised when there is an indentation error in your code, such as mismatched indentation levels.<\/span><\/p>\n<p><span style=\"color: #000000;\"><strong>3. `NameError`:<\/strong> Raised when a local or global name is not found.<\/span><\/p>\n<p><span style=\"color: #000000;\"><strong>4. `TypeError`:<\/strong> Raised when an operation or function is applied to an object of inappropriate type.<\/span><\/p>\n<p><span style=\"color: #000000;\"><strong>5. `ValueError`:<\/strong> Raised when an operation or function receives an argument of the correct type but an inappropriate value.<\/span><\/p>\n<p><span style=\"color: #000000;\"><strong>6. `KeyError`:<\/strong> Raised when a dictionary is accessed with a key that doesn&#8217;t exist.<\/span><\/p>\n<p><span style=\"color: #000000;\"><strong>7. `IndexError`:<\/strong> Raised when trying to access an element at an invalid index in a sequence (e.g., list, tuple).<\/span><\/p>\n<p><span style=\"color: #000000;\"><strong>8. `FileNotFoundError`:<\/strong> Raised when trying to open or manipulate a file that does not exist.<\/span><\/p>\n<p><span style=\"color: #000000;\"><strong>9. `IOError`:<\/strong> Raised for I\/O-related errors, such as when reading or writing to a file fails.<\/span><\/p>\n<p><span style=\"color: #000000;\"><strong>10. `ZeroDivisionError`:<\/strong> Raised when attempting to divide by zero.<\/span><\/p>\n<p><span style=\"color: #000000;\"><strong>11. `AttributeError`:<\/strong> Raised when an attribute reference or assignment fails.<\/span><\/p>\n<p><span style=\"color: #000000;\"><strong>12. `ImportError`:<\/strong> Raised when an import statement fails to find the module.<\/span><\/p>\n<p><span style=\"color: #000000;\"><strong>13. `TypeError`:<\/strong> Raised when an incorrect type is passed as an argument to a function or method.<\/span><\/p>\n<p><span style=\"color: #000000;\"><strong>14. `AssertionError`:<\/strong> Raised when an `assert` statement fails.<\/span><\/p>\n<p><span style=\"color: #000000;\"><strong>15. `KeyboardInterrupt`:<\/strong> Raised when the user interrupts the program (e.g., by pressing Ctrl+C).<\/span><\/p>\n<p><span style=\"color: #000000;\"><strong>16. `EOFError`:<\/strong> Raised when an input operation reaches the end of the file.<\/span><\/p>\n<p><span style=\"color: #000000;\"><strong>17. `ArithmeticError`:<\/strong> A base class for numeric errors, including `ZeroDivisionError` and `OverflowError`.<\/span><\/p>\n<p><span style=\"color: #000000;\"><strong>18. `FileExistsError`:<\/strong> Raised when trying to create a file or directory that already exists.<\/span><\/p>\n<p><span style=\"color: #000000;\"><strong>19. `FileNotFoundError`:<\/strong> Raised when trying to access a file or directory that does not exist.<\/span><\/p>\n<p><span style=\"color: #000000;\"><strong>20. `PermissionError`:<\/strong> Raised when trying to perform an operation without the necessary permissions.<\/span><\/p>\n<p>&nbsp;<\/p>\n<h3><span style=\"color: #000000;\">Handling Multiple Exceptions<\/span><\/h3>\n<p><span style=\"color: #000000;\">In Python, you can handle multiple exceptions in the same program by using multiple except blocks within a try block. Each except block is responsible for handling a specific type of exception. <\/span><\/p>\n<p><span style=\"color: #000000;\">Here&#8217;s an example that demonstrates how to handle different exceptions:<\/span><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">def divide_numbers(a, b):\r\n    try:\r\n        result = a \/ b\r\n    except ZeroDivisionError:\r\n        print(\"Error: Division by zero!\")\r\n        result = None\r\n    except ValueError:\r\n        print(\"Error: Invalid input value!\")\r\n        result = None\r\n    except TypeError:\r\n        print(\"Error: Invalid data type!\")\r\n        result = None\r\n    except Exception as e:\r\n        print(f\"An unexpected error occurred: {e}\")\r\n        result = None\r\n    finally:\r\n        print(\"Exception Handing in Python...\")\r\n    \r\n    return result\r\n\r\n# Example 1: Division without error\r\nresult1 = divide_numbers(10, 2)\r\nprint(\"Result 1:\", result1)\r\n\r\n# Example 2: Division by zero (ZeroDivisionError)\r\nresult2 = divide_numbers(5, 0)\r\nprint(\"Result 2:\", result2)\r\n\r\n# Example 3: Invalid input value (ValueError)\r\nresult3 = divide_numbers(10, \"2\")\r\nprint(\"Result 3:\", result3)\r\n\r\n# Example 4: Invalid data type (TypeError)\r\nresult4 = divide_numbers(\"10\", 2)\r\nprint(\"Result 4:\", result4)\r\n<\/pre>\n<p>&nbsp;<\/p>\n<p><strong><span style=\"color: #000000;\">Output:<\/span><\/strong><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone wp-image-4222 size-full\" src=\"https:\/\/cbsepython.in\/wp-content\/uploads\/2023\/09\/Handling-Multiple-Exceptions.jpg\" alt=\"Handling Multiple Exceptions\" width=\"465\" height=\"268\" title=\"\" srcset=\"https:\/\/cbsepython.in\/wp-content\/uploads\/2023\/09\/Handling-Multiple-Exceptions.jpg 465w, https:\/\/cbsepython.in\/wp-content\/uploads\/2023\/09\/Handling-Multiple-Exceptions-300x173.jpg 300w\" sizes=\"(max-width: 465px) 100vw, 465px\" \/><\/p>\n<p><span style=\"color: #000000;\">In this example, we have a divide_numbers function that performs division and handles multiple exceptions:<\/span><\/p>\n<p><span style=\"color: #000000;\">ZeroDivisionError is raised when attempting to divide by zero.<\/span><br \/>\n<span style=\"color: #000000;\">ValueError is raised if the input values cannot be converted to numeric types.<\/span><br \/>\n<span style=\"color: #000000;\">TypeError is raised if the data types of the input values are incompatible with division.<\/span><br \/>\n<span style=\"color: #000000;\">The generic Exception block is used to catch any unexpected exceptions and display an error message.<\/span><br \/>\n<span style=\"color: #000000;\">Each exception type is handled separately, allowing the program to provide appropriate error messages and perform cleanup operations for each case.<\/span><\/p>\n<p>&nbsp;<\/p>\n<p style=\"text-align: center;\"><span style=\"text-decoration: underline; color: #000000;\">Exception Handling in Python<\/span><\/p>\n<h3><span style=\"color: #000000;\">\u00a0The `finally` Block<\/span><\/h3>\n<p><span style=\"color: #000000;\">&#8211; The `finally` block contains code that must execute, whether or not an exception was raised in the `try` block.<\/span><\/p>\n<p><span style=\"color: #000000;\">&#8211; It ensures that certain actions are taken regardless of the outcome.<\/span><\/p>\n<p>&nbsp;<\/p>\n<p><span style=\"color: #000000;\">In Python, the finally block is an essential part of exception handling, working alongside the try and except blocks. It allows you to define code that will execute regardless of whether an exception is raised or not. This can be particularly useful for tasks such as closing files, releasing resources, or performing cleanup operations to ensure that your program remains in a consistent state.<\/span><\/p>\n<p>&nbsp;<\/p>\n<p><span style=\"color: #000000;\">Here&#8217;s the basic structure of a try&#8230;except&#8230;finally block in Python:<\/span><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">try:\r\n    # Code that may raise an exception\r\n    # ...\r\nexcept SomeException:\r\n    # Handle the exception if it occurs\r\n    # ...\r\nfinally:\r\n    # Code that always runs, whether an exception occurred or not\r\n    # ...<\/pre>\n<p>&nbsp;<\/p>\n<h3><span style=\"color: #000000;\">Finally Block Example<\/span><\/h3>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">def divide_numbers(a, b):\r\n    try:\r\n        result = a \/ b\r\n    except ZeroDivisionError:\r\n        print(\"Error: Division by zero!\")\r\n        result = None\r\n    finally:\r\n        print(\"Notes Exception Handling in Python Class 12...\")\r\n        # This code will always run, even if an exception occurred or not\r\n    \r\n    return result\r\n\r\n# Example 1: Division without error\r\nresult1 = divide_numbers(10, 2)\r\nprint(\"Result 1:\", result1)\r\n\r\n# Example 2: Division by zero (error)\r\nresult2 = divide_numbers(5, 0)\r\nprint(\"Result 2:\", result2)\r\n<\/pre>\n<p><span style=\"color: #000000;\">Output:<\/span><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone wp-image-4219 size-full\" src=\"https:\/\/cbsepython.in\/wp-content\/uploads\/2023\/09\/finally-Block.jpg\" alt=\"Exception Handling in Python Class 12 Notes\" width=\"676\" height=\"135\" title=\"\" srcset=\"https:\/\/cbsepython.in\/wp-content\/uploads\/2023\/09\/finally-Block.jpg 676w, https:\/\/cbsepython.in\/wp-content\/uploads\/2023\/09\/finally-Block-300x60.jpg 300w\" sizes=\"(max-width: 676px) 100vw, 676px\" \/><\/p>\n<p>&nbsp;<\/p>\n<p><span style=\"color: #000000;\">In this example, the divide_numbers function attempts to divide two numbers. If a ZeroDivisionError occurs (division by zero), it is caught in the except block. However, the finally block is executed in both cases to perform cleanup operations.<\/span><\/p>\n<p><span style=\"color: #000000;\">Here are some key points to remember about the finally block in Python exception handling:<\/span><\/p>\n<p><span style=\"color: #000000;\">The finally block is optional but useful for ensuring that critical cleanup operations are performed, even in the presence of exceptions.<\/span><\/p>\n<p><span style=\"color: #000000;\">The code inside the finally block will run regardless of whether an exception is raised or not. It is guaranteed to execute.<\/span><\/p>\n<p><span style=\"color: #000000;\">You can use the finally block to close files, release resources, or perform any other necessary cleanup tasks.<\/span><\/p>\n<p><span style=\"color: #000000;\">If there is a return statement in the finally block, it will override any return value set in the try or except blocks. So, be cautious when using return within the finally block.<\/span><\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p style=\"text-align: center;\"><span style=\"text-decoration: underline; color: #000000;\">Exception Handling in Python<\/span><\/p>\n<h2><span style=\"color: #000000;\">\u00a0Raising\/Forcing an Exception<\/span><\/h2>\n<p><span style=\"color: #000000;\">&#8211; You can raise exceptions manually using the `raise` keyword.<\/span><\/p>\n<p><span style=\"color: #000000;\">&#8211; Syntax: `raise &lt;exception&gt;(&lt;message&gt;)` (The exception should be a pre-defined built-in exception.)<\/span><\/p>\n<p>&nbsp;<\/p>\n<h3><span style=\"color: #000000;\">\u00a0Benefits of Exception Handling<\/span><\/h3>\n<p><span style=\"color: #000000;\">&#8211; Exception handling separates error-handling code from normal code.<\/span><\/p>\n<p><span style=\"color: #000000;\">&#8211; It enhances code readability and clarity.<\/span><\/p>\n<p><span style=\"color: #000000;\">&#8211; It promotes consistent error-handling practices.<\/span><\/p>\n<p><span style=\"color: #000000;\">&#8211; It leads to clear, robust, and fault-tolerant programs.<\/span><\/p>\n<p>&nbsp;<\/p>\n<p style=\"text-align: center;\"><span style=\"text-decoration: underline; color: #000000;\">Exception Handling in Python<\/span><\/p>\n<h2><span style=\"color: #000000;\">\u00a0File Operations<\/span><\/h2>\n<h3><span style=\"color: #000000;\">\u00a0`seek()`<\/span><\/h3>\n<p><span style=\"color: #000000;\">&#8211; Used to change the position of the file pointer to a specific location.<\/span><\/p>\n<p><span style=\"color: #000000;\">&#8211; The file pointer is like a cursor indicating where data should be read or written in the file.<\/span><\/p>\n<p><span style=\"color: #000000;\">&#8211; Syntax: `f.seek(file_location)` or `f.seek(offset, from_what)`<\/span><\/p>\n<p><span style=\"color: #000000;\">\u00a0 &#8211; `0`: Sets the reference point at the beginning of the file (default).<\/span><\/p>\n<p><span style=\"color: #000000;\">\u00a0 &#8211; `1`: Sets the reference point at the current file position.<\/span><\/p>\n<p><span style=\"color: #000000;\">\u00a0 &#8211; `2`: Sets the reference point at the end of the file.<\/span><\/p>\n<p>&nbsp;<\/p>\n<h3><span style=\"color: #000000;\">\u00a0`tell()`<\/span><\/h3>\n<p><span style=\"color: #000000;\">&#8211; Tells the current position of the file pointer.<\/span><\/p>\n<p><span style=\"color: #000000;\">&#8211; In &#8216;r&#8217; and &#8216;w&#8217; mode, the file pointer is at the beginning of the file.<\/span><\/p>\n<p><span style=\"color: #000000;\">&#8211; In &#8216;a&#8217; mode, the file pointer is at the end of the file when using `tell()`.<\/span><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Exception Handling in Python Here students of class 12 will learn about the \u00a0Exception Handling in Python. These notes are made to help the students in their board preparation. The topic \u00a0Exception Handling is introduced by the CBSE for the session 2023-24 onward.\u00a0 Errors Errors in a program can be categorized into following types: 1. [&hellip;]<\/p>\n","protected":false},"author":3,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[16,20],"tags":[],"class_list":["post-4204","post","type-post","status-publish","format-standard","hentry","category-cbse-sample-papers-class-12","category-cbse-computer-science-with-python-class-12"],"_links":{"self":[{"href":"https:\/\/cbsepython.in\/wp-json\/wp\/v2\/posts\/4204","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/cbsepython.in\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/cbsepython.in\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/cbsepython.in\/wp-json\/wp\/v2\/users\/3"}],"replies":[{"embeddable":true,"href":"https:\/\/cbsepython.in\/wp-json\/wp\/v2\/comments?post=4204"}],"version-history":[{"count":0,"href":"https:\/\/cbsepython.in\/wp-json\/wp\/v2\/posts\/4204\/revisions"}],"wp:attachment":[{"href":"https:\/\/cbsepython.in\/wp-json\/wp\/v2\/media?parent=4204"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/cbsepython.in\/wp-json\/wp\/v2\/categories?post=4204"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/cbsepython.in\/wp-json\/wp\/v2\/tags?post=4204"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}