{"id":2654,"date":"2026-10-19T11:00:23","date_gmt":"2026-10-19T11:00:23","guid":{"rendered":"https:\/\/prwatech.in\/blog\/?p=2654"},"modified":"2026-10-20T06:21:17","modified_gmt":"2026-10-20T06:21:17","slug":"python-exception-handling-tutorial","status":"publish","type":"post","link":"https:\/\/prwatech.in\/blog\/python\/python-exception-handling\/python-exception-handling-tutorial\/","title":{"rendered":"Python Exception Handling Tutorial"},"content":{"rendered":"<h1><strong><b>Python Exception Handling Tutorial: try, except, else and finally<\/b><\/strong><\/h1>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">A program that works on your own test data can still break the moment a real user touches it. Someone types a word where you expected a number. A file is missing. A network call times out. A list is shorter than you thought. Without any protection, Python stops at the first problem and prints a long message that means nothing to the user.<\/p>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">Exception handling is how you stay in control when this happens. You tell Python which lines might fail, what to do if they do, and what must always run afterward, such as closing a file. Done well, a program turns a crash into a clear message or a safe fallback, and it keeps running.<\/p>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">In this tutorial, we explain what an error and an exception are, and how Python reacts when one is not handled. We then go through the try and except blocks, handling more than one error, the else and finally blocks, the raise statement, custom exceptions, and file errors. Every program has been run. We finish with the order of except blocks, the exception hierarchy, and the mistakes to avoid.<\/p>\n<p style=\"margin: 0 0 16px;\"><img loading=\"lazy\" decoding=\"async\" style=\"display: block; max-width: 100%; height: auto; margin: 0 auto; border: 1px solid #d9e0ea; border-radius: 8px;\" src=\"https:\/\/prwatech.in\/blog\/wp-content\/uploads\/2019\/07\/Untitled-design-1-1024x576.png\" alt=\"Python exception handling tutorial with try, except, else and finally\" width=\"840\" height=\"473\" \/><\/p>\n<h2 style=\"font-family: Arial,Helvetica,sans-serif; font-size: 26px; line-height: 1.3; font-weight: bold; color: #0f2a4a; margin: 36px 0 12px;\">What is an Error in Python?<\/h2>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">Python has two kinds of errors.<\/p>\n<ul style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px; padding-left: 24px;\">\n<li style=\"margin: 0 0 8px;\"><strong>Syntax errors<\/strong> are mistakes in how the code is written, such as a missing bracket. Python finds them before the program runs, and the program does not start at all.<\/li>\n<li style=\"margin: 0 0 8px;\"><strong>Exceptions<\/strong> are errors that happen while the program is running, even though the code is written correctly. Dividing by zero is one example. Python stops the current line, shows a message, and ends the program, unless you handle it.<\/li>\n<\/ul>\n<div style=\"margin: 20px 0; border: 1px solid #d9e0ea; border-radius: 8px; overflow: hidden;\">\n<div style=\"background: #0f2a4a; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">python<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #f5f8fc;\">try:\r\n    compile(\"print('hello'\", \"&lt;test&gt;\", \"exec\")\r\nexcept SyntaxError as e:\r\n    print(\"SyntaxError:\", e.msg)<\/pre>\n<div style=\"background: #1f2937; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">output<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #ffffff;\">SyntaxError: '(' was never closed<\/pre>\n<\/div>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">The difference matters, because try and except can handle exceptions, and a syntax error is something you fix in the code.<\/p>\n<h2 style=\"font-family: Arial,Helvetica,sans-serif; font-size: 26px; line-height: 1.3; font-weight: bold; color: #0f2a4a; margin: 36px 0 12px;\">Common Built In Exceptions<\/h2>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">These are the exceptions you will meet most, each with the real message Python gives.<\/p>\n<div style=\"border: 1px solid #d9e0ea; border-radius: 8px; overflow-x: auto; margin: 20px 0; -webkit-overflow-scrolling: touch;\">\n<table style=\"width: 100%; min-width: 760px; border-collapse: collapse; font-family: Arial,Helvetica,sans-serif; font-size: 16px; line-height: 1.6; color: #1f2937;\">\n<caption style=\"caption-side: top; text-align: left; padding: 14px 16px; font-weight: bold; font-size: 17px; color: #0f2a4a;\">Common exceptions and their messages<\/caption>\n<thead>\n<tr>\n<th style=\"background: #0f2a4a; color: #ffffff; text-align: left; padding: 12px 16px; border-bottom: 2px solid #0b1f38;\" scope=\"col\">Exception<\/th>\n<th style=\"background: #0f2a4a; color: #ffffff; text-align: left; padding: 12px 16px; border-bottom: 2px solid #0b1f38;\" scope=\"col\">When it happens<\/th>\n<th style=\"background: #0f2a4a; color: #ffffff; text-align: left; padding: 12px 16px; border-bottom: 2px solid #0b1f38;\" scope=\"col\">Real message<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr style=\"background: #ffffff;\">\n<th style=\"text-align: left; padding: 12px 16px; border-bottom: 1px solid #e5e9f0; color: #0f2a4a; font-family: 'Courier New',Courier,monospace; font-size: 15px; white-space: nowrap;\" scope=\"row\">ZeroDivisionError<\/th>\n<td style=\"padding: 12px 16px; border-bottom: 1px solid #e5e9f0;\">Dividing by zero<\/td>\n<td style=\"padding: 12px 16px; border-bottom: 1px solid #e5e9f0; font-family: 'Courier New',Courier,monospace; font-size: 15px; white-space: nowrap;\">division by zero<\/td>\n<\/tr>\n<tr style=\"background: #f5f8fc;\">\n<th style=\"text-align: left; padding: 12px 16px; border-bottom: 1px solid #e5e9f0; color: #0f2a4a; font-family: 'Courier New',Courier,monospace; font-size: 15px; white-space: nowrap;\" scope=\"row\">NameError<\/th>\n<td style=\"padding: 12px 16px; border-bottom: 1px solid #e5e9f0;\">Using a name that does not exist<\/td>\n<td style=\"padding: 12px 16px; border-bottom: 1px solid #e5e9f0; font-family: 'Courier New',Courier,monospace; font-size: 15px; white-space: nowrap;\">name &#8216;undefined_name&#8217; is not defined<\/td>\n<\/tr>\n<tr style=\"background: #ffffff;\">\n<th style=\"text-align: left; padding: 12px 16px; border-bottom: 1px solid #e5e9f0; color: #0f2a4a; font-family: 'Courier New',Courier,monospace; font-size: 15px; white-space: nowrap;\" scope=\"row\">IndexError<\/th>\n<td style=\"padding: 12px 16px; border-bottom: 1px solid #e5e9f0;\">A list position is out of range<\/td>\n<td style=\"padding: 12px 16px; border-bottom: 1px solid #e5e9f0; font-family: 'Courier New',Courier,monospace; font-size: 15px; white-space: nowrap;\">list index out of range<\/td>\n<\/tr>\n<tr style=\"background: #f5f8fc;\">\n<th style=\"text-align: left; padding: 12px 16px; border-bottom: 1px solid #e5e9f0; color: #0f2a4a; font-family: 'Courier New',Courier,monospace; font-size: 15px; white-space: nowrap;\" scope=\"row\">KeyError<\/th>\n<td style=\"padding: 12px 16px; border-bottom: 1px solid #e5e9f0;\">A dictionary key is missing<\/td>\n<td style=\"padding: 12px 16px; border-bottom: 1px solid #e5e9f0; font-family: 'Courier New',Courier,monospace; font-size: 15px; white-space: nowrap;\">&#8216;b&#8217;<\/td>\n<\/tr>\n<tr style=\"background: #ffffff;\">\n<th style=\"text-align: left; padding: 12px 16px; border-bottom: 1px solid #e5e9f0; color: #0f2a4a; font-family: 'Courier New',Courier,monospace; font-size: 15px; white-space: nowrap;\" scope=\"row\">ValueError<\/th>\n<td style=\"padding: 12px 16px; border-bottom: 1px solid #e5e9f0;\">Right type, wrong value<\/td>\n<td style=\"padding: 12px 16px; border-bottom: 1px solid #e5e9f0; font-family: 'Courier New',Courier,monospace; font-size: 15px; white-space: nowrap;\">invalid literal for int() with base 10: &#8216;abc&#8217;<\/td>\n<\/tr>\n<tr style=\"background: #f5f8fc;\">\n<th style=\"text-align: left; padding: 12px 16px; border-bottom: 1px solid #e5e9f0; color: #0f2a4a; font-family: 'Courier New',Courier,monospace; font-size: 15px; white-space: nowrap;\" scope=\"row\">TypeError<\/th>\n<td style=\"padding: 12px 16px; border-bottom: 1px solid #e5e9f0;\">Wrong type for an operation<\/td>\n<td style=\"padding: 12px 16px; border-bottom: 1px solid #e5e9f0; font-family: 'Courier New',Courier,monospace; font-size: 15px; white-space: nowrap;\">can only concatenate str (not &#8220;int&#8221;) to str<\/td>\n<\/tr>\n<tr style=\"background: #ffffff;\">\n<th style=\"text-align: left; padding: 12px 16px; color: #0f2a4a; font-family: 'Courier New',Courier,monospace; font-size: 15px; white-space: nowrap;\" scope=\"row\">FileNotFoundError<\/th>\n<td style=\"padding: 12px 16px;\">The file does not exist<\/td>\n<td style=\"padding: 12px 16px; font-family: 'Courier New',Courier,monospace; font-size: 15px; white-space: nowrap;\">[Errno 2] No such file or directory<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/div>\n<h2 style=\"font-family: Arial,Helvetica,sans-serif; font-size: 26px; line-height: 1.3; font-weight: bold; color: #0f2a4a; margin: 36px 0 12px;\">The Effect of Exception Handling<\/h2>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">An exception changes the normal flow of a program. When one is raised, Python stops running the lines in order and looks for a handler. If it finds an except block that matches, it runs that block and carries on after the whole try statement. If it finds none, the program ends right away and prints a traceback.<\/p>\n<h2 style=\"font-family: Arial,Helvetica,sans-serif; font-size: 26px; line-height: 1.3; font-weight: bold; color: #0f2a4a; margin: 36px 0 12px;\">How Python Handles an Exception<\/h2>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">Python reads the try block line by line. If no line fails, the except blocks are skipped. If a line fails, Python jumps out of the try block at once, and the lines after the failing one do not run. It then picks the first except block that matches the error type.<\/p>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">Handling exceptions gives you three real benefits.<\/p>\n<ul style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px; padding-left: 24px;\">\n<li style=\"margin: 0 0 8px;\"><strong>Cleaner code.<\/strong> The normal path and the error path are separate, so you do not wrap every line in an if check.<\/li>\n<li style=\"margin: 0 0 8px;\"><strong>One consistent way to deal with errors.<\/strong> Every library you use reports problems in the same way.<\/li>\n<li style=\"margin: 0 0 8px;\"><strong>A program that does not crash.<\/strong> It can show a clear message, use a default, or try again.<\/li>\n<\/ul>\n<h2 style=\"font-family: Arial,Helvetica,sans-serif; font-size: 26px; line-height: 1.3; font-weight: bold; color: #0f2a4a; margin: 36px 0 12px;\">Exception Handling Example<\/h2>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">The first print works. The second asks for index 4 in a list that has only four items, so Python raises an IndexError, and the except block runs.<\/p>\n<div style=\"margin: 20px 0; border: 1px solid #d9e0ea; border-radius: 8px; overflow: hidden;\">\n<div style=\"background: #0f2a4a; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">python<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #f5f8fc;\">test = [1, 2, 4, 8]\r\ntry:\r\n    print(\"First element = %d\" % (test[0]))\r\n    # Only 4 elements, so index 4 raises an IndexError\r\n    print(\"Fifth element = %d\" % (test[4]))\r\nexcept IndexError:\r\n    print(\"Error occurred\")<\/pre>\n<div style=\"background: #1f2937; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">output<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #ffffff;\">First element = 1\r\nError occurred<\/pre>\n<\/div>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">Notice that the first line printed before the error, because the lines before the failure run normally.<\/p>\n<h3 style=\"font-family: Arial,Helvetica,sans-serif; font-size: 21px; line-height: 1.35; font-weight: bold; color: #0f2a4a; margin: 28px 0 10px;\">Reading the Error Message<\/h3>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">You can catch the error as a variable with the word <code style=\"font-family: 'Courier New',Courier,monospace; font-size: 15px; background: #eef2f7; padding: 2px 6px; border-radius: 4px;\">as<\/code>, and print the message Python gives. This helps when you need to know what went wrong.<\/p>\n<div style=\"margin: 20px 0; border: 1px solid #d9e0ea; border-radius: 8px; overflow: hidden;\">\n<div style=\"background: #0f2a4a; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">python<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #f5f8fc;\">try:\r\n    int(\"abc\")\r\nexcept ValueError as e:\r\n    print(\"Error:\", e)<\/pre>\n<div style=\"background: #1f2937; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">output<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #ffffff;\">Error: invalid literal for int() with base 10: 'abc'<\/pre>\n<\/div>\n<h2 style=\"font-family: Arial,Helvetica,sans-serif; font-size: 26px; line-height: 1.3; font-weight: bold; color: #0f2a4a; margin: 36px 0 12px;\">Multiple Exception Handling Example<\/h2>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">A block of code can fail in more than one way. You have two choices. You can catch several types in one except line, by putting them in round brackets as a tuple. Or you can write a separate except block for each type, so each error gets its own response.<\/p>\n<h3 style=\"font-family: Arial,Helvetica,sans-serif; font-size: 21px; line-height: 1.35; font-weight: bold; color: #0f2a4a; margin: 28px 0 10px;\">One Handler for Several Errors<\/h3>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">The brackets are required. This example can fail in both ways. For the value 5, the division is by zero. For the text seven, Python cannot subtract a number from text.<\/p>\n<div style=\"margin: 20px 0; border: 1px solid #d9e0ea; border-radius: 8px; overflow: hidden;\">\n<div style=\"background: #0f2a4a; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">python<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #f5f8fc;\">def calculate(vari):\r\n    try:\r\n        cal = 100 \/ (vari - 5)\r\n        print(\"value of cal =\", cal)\r\n    except (ZeroDivisionError, TypeError):\r\n        print(\"Error handled\")\r\n \r\ncalculate(5)\r\ncalculate(7)\r\ncalculate(\"seven\")<\/pre>\n<div style=\"background: #1f2937; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">output<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #ffffff;\">Error handled\r\nvalue of cal = 50.0\r\nError handled<\/pre>\n<\/div>\n<h3 style=\"font-family: Arial,Helvetica,sans-serif; font-size: 21px; line-height: 1.35; font-weight: bold; color: #0f2a4a; margin: 28px 0 10px;\">A Separate Handler for Each Error<\/h3>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">When the right response is different for each error, give each its own block. Python checks them from top to bottom and runs only the first match.<\/p>\n<div style=\"margin: 20px 0; border: 1px solid #d9e0ea; border-radius: 8px; overflow: hidden;\">\n<div style=\"background: #0f2a4a; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">python<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #f5f8fc;\">def divide(a, b):\r\n    try:\r\n        result = a \/ b\r\n    except ZeroDivisionError:\r\n        print(\"You cannot divide by zero\")\r\n    except TypeError:\r\n        print(\"Both values must be numbers\")\r\n    else:\r\n        print(\"Result:\", result)\r\n    finally:\r\n        print(\"Division attempted\")\r\n \r\ndivide(10, 2)\r\ndivide(10, 0)\r\ndivide(10, \"2\")<\/pre>\n<div style=\"background: #1f2937; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">output<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #ffffff;\">Result: 5.0\r\nDivision attempted\r\nYou cannot divide by zero\r\nDivision attempted\r\nBoth values must be numbers\r\nDivision attempted<\/pre>\n<\/div>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">At most one except block runs for each error.<\/p>\n<h2 style=\"font-family: Arial,Helvetica,sans-serif; font-size: 26px; line-height: 1.3; font-weight: bold; color: #0f2a4a; margin: 36px 0 12px;\">The else and finally Statements<\/h2>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">Two optional blocks make a try statement more useful.<\/p>\n<div style=\"border: 1px solid #d9e0ea; border-radius: 8px; overflow-x: auto; margin: 20px 0; -webkit-overflow-scrolling: touch;\">\n<table style=\"width: 100%; min-width: 640px; border-collapse: collapse; font-family: Arial,Helvetica,sans-serif; font-size: 16px; line-height: 1.6; color: #1f2937;\">\n<caption style=\"caption-side: top; text-align: left; padding: 14px 16px; font-weight: bold; font-size: 17px; color: #0f2a4a;\">else and finally<\/caption>\n<thead>\n<tr>\n<th style=\"background: #0f2a4a; color: #ffffff; text-align: left; padding: 12px 16px; border-bottom: 2px solid #0b1f38;\" scope=\"col\">Block<\/th>\n<th style=\"background: #0f2a4a; color: #ffffff; text-align: left; padding: 12px 16px; border-bottom: 2px solid #0b1f38;\" scope=\"col\">When it runs<\/th>\n<th style=\"background: #0f2a4a; color: #ffffff; text-align: left; padding: 12px 16px; border-bottom: 2px solid #0b1f38;\" scope=\"col\">Typical use<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr style=\"background: #ffffff;\">\n<th style=\"text-align: left; padding: 12px 16px; border-bottom: 1px solid #e5e9f0; color: #0f2a4a; font-family: 'Courier New',Courier,monospace; font-size: 15px; white-space: nowrap;\" scope=\"row\">else<\/th>\n<td style=\"padding: 12px 16px; border-bottom: 1px solid #e5e9f0;\">Only when the try block raised no exception<\/td>\n<td style=\"padding: 12px 16px; border-bottom: 1px solid #e5e9f0;\">Code that should run only if everything worked<\/td>\n<\/tr>\n<tr style=\"background: #f5f8fc;\">\n<th style=\"text-align: left; padding: 12px 16px; color: #0f2a4a; font-family: 'Courier New',Courier,monospace; font-size: 15px; white-space: nowrap;\" scope=\"row\">finally<\/th>\n<td style=\"padding: 12px 16px;\">Always, whether or not there was an error<\/td>\n<td style=\"padding: 12px 16px;\">Cleanup, such as closing a file or a connection<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/div>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">The function below turns an age into days. For 20, nothing fails, so else and finally both run. For 20.5, the conversion to an int raises a ValueError, so the except block runs and then finally runs.<\/p>\n<div style=\"margin: 20px 0; border: 1px solid #d9e0ea; border-radius: 8px; overflow: hidden;\">\n<div style=\"background: #0f2a4a; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">python<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #f5f8fc;\">def print_age_in_days(years):\r\n    print(\"Your age in days is about\", 365 * int(years))\r\n \r\ndef check_age(age):\r\n    try:\r\n        print_age_in_days(age)\r\n    except ValueError:\r\n        print(\"You did not enter an age as a whole number\")\r\n    else:\r\n        print(age, \"successfully converted into days\")\r\n    finally:\r\n        print(\"Input test complete\")\r\n \r\ncheck_age(\"20\")\r\ncheck_age(\"20.5\")<\/pre>\n<div style=\"background: #1f2937; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">output<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #ffffff;\">Your age in days is about 7300\r\n20 successfully converted into days\r\nInput test complete\r\nYou did not enter an age as a whole number\r\nInput test complete<\/pre>\n<\/div>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">In a real program the age would come from the <code style=\"font-family: 'Courier New',Courier,monospace; font-size: 15px; background: #eef2f7; padding: 2px 6px; border-radius: 4px;\">input<\/code> function. We pass it in as text here so the example runs without waiting for typing.<\/p>\n<h2 style=\"font-family: Arial,Helvetica,sans-serif; font-size: 26px; line-height: 1.3; font-weight: bold; color: #0f2a4a; margin: 36px 0 12px;\">Raise an Exception in Python<\/h2>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">So far Python raised the errors. You can also raise one yourself, with the <code style=\"font-family: 'Courier New',Courier,monospace; font-size: 15px; background: #eef2f7; padding: 2px 6px; border-radius: 4px;\">raise<\/code> statement. This is how you reject bad data early, with a clear message, before it causes a confusing problem later.<\/p>\n<h3 style=\"font-family: Arial,Helvetica,sans-serif; font-size: 21px; line-height: 1.35; font-weight: bold; color: #0f2a4a; margin: 28px 0 10px;\">The raise Statement<\/h3>\n<div style=\"margin: 20px 0; border: 1px solid #d9e0ea; border-radius: 8px; overflow: hidden;\">\n<div style=\"background: #0f2a4a; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">python<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #f5f8fc;\">def set_age(age):\r\n    if age &lt; 0:\r\n        raise ValueError(\"Age cannot be negative\")\r\n    return age\r\n \r\ntry:\r\n    set_age(-5)\r\nexcept ValueError as e:\r\n    print(\"Error:\", e)<\/pre>\n<div style=\"background: #1f2937; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">output<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #ffffff;\">Error: Age cannot be negative<\/pre>\n<\/div>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">The plainest form raises a NameError by hand, just to show the syntax:<\/p>\n<div style=\"margin: 20px 0; border: 1px solid #d9e0ea; border-radius: 8px; overflow: hidden;\">\n<div style=\"background: #0f2a4a; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">python<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #f5f8fc;\">try:\r\n    raise NameError(\"Python code\")\r\nexcept NameError as e:\r\n    print(\"Exception:\", e)<\/pre>\n<div style=\"background: #1f2937; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">output<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #ffffff;\">Exception: Python code<\/pre>\n<\/div>\n<h3 style=\"font-family: Arial,Helvetica,sans-serif; font-size: 21px; line-height: 1.35; font-weight: bold; color: #0f2a4a; margin: 28px 0 10px;\">Raising the Same Error Again<\/h3>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">A bare <code style=\"font-family: 'Courier New',Courier,monospace; font-size: 15px; background: #eef2f7; padding: 2px 6px; border-radius: 4px;\">raise<\/code>, with nothing after it, inside an except block, sends the same exception up to the next handler. If there is no outer handler, Python runs the inner block and then stops with a traceback ending in <code style=\"font-family: 'Courier New',Courier,monospace; font-size: 15px; background: #eef2f7; padding: 2px 6px; border-radius: 4px;\">NameError: Python code<\/code>. With an outer handler, it works as you would expect:<\/p>\n<div style=\"margin: 20px 0; border: 1px solid #d9e0ea; border-radius: 8px; overflow: hidden;\">\n<div style=\"background: #0f2a4a; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">python<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #f5f8fc;\">try:\r\n    try:\r\n        raise NameError(\"Python code\")\r\n    except NameError:\r\n        print(\"Inner handler ran\")\r\n        raise\r\nexcept NameError as e:\r\n    print(\"Outer handler caught:\", e)<\/pre>\n<div style=\"background: #1f2937; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">output<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #ffffff;\">Inner handler ran\r\nOuter handler caught: Python code<\/pre>\n<\/div>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">Use this when a function wants to log or clean up after an error, and still let the caller decide what to do.<\/p>\n<h2 style=\"font-family: Arial,Helvetica,sans-serif; font-size: 26px; line-height: 1.3; font-weight: bold; color: #0f2a4a; margin: 36px 0 12px;\">Create Your Own Exception<\/h2>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">When the built in exceptions do not describe your problem, make your own by writing a class that inherits from <code style=\"font-family: 'Courier New',Courier,monospace; font-size: 15px; background: #eef2f7; padding: 2px 6px; border-radius: 4px;\">Exception<\/code>. It gives your error a clear name that the rest of the program can catch.<\/p>\n<div style=\"margin: 20px 0; border: 1px solid #d9e0ea; border-radius: 8px; overflow: hidden;\">\n<div style=\"background: #0f2a4a; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">python<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #f5f8fc;\">class LowBalanceError(Exception):\r\n    pass\r\n \r\ndef withdraw(balance, amount):\r\n    if amount &gt; balance:\r\n        raise LowBalanceError(f\"Balance {balance} is less than {amount}\")\r\n    return balance - amount\r\n \r\ntry:\r\n    withdraw(500, 800)\r\nexcept LowBalanceError as e:\r\n    print(\"Custom error:\", e)<\/pre>\n<div style=\"background: #1f2937; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">output<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #ffffff;\">Custom error: Balance 500 is less than 800<\/pre>\n<\/div>\n<h2 style=\"font-family: Arial,Helvetica,sans-serif; font-size: 26px; line-height: 1.3; font-weight: bold; color: #0f2a4a; margin: 36px 0 12px;\">Opening Files and Exceptions<\/h2>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">Files are the most common place where exceptions happen, because a file can be missing, locked, or without permission. Opening a file that does not exist raises a <code style=\"font-family: 'Courier New',Courier,monospace; font-size: 15px; background: #eef2f7; padding: 2px 6px; border-radius: 4px;\">FileNotFoundError<\/code>. This is a kind of <code style=\"font-family: 'Courier New',Courier,monospace; font-size: 15px; background: #eef2f7; padding: 2px 6px; border-radius: 4px;\">OSError<\/code>. In Python 3, the name <code style=\"font-family: 'Courier New',Courier,monospace; font-size: 15px; background: #eef2f7; padding: 2px 6px; border-radius: 4px;\">IOError<\/code> is only another name for <code style=\"font-family: 'Courier New',Courier,monospace; font-size: 15px; background: #eef2f7; padding: 2px 6px; border-radius: 4px;\">OSError<\/code>.<\/p>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">The error object carries useful details. The attribute <code style=\"font-family: 'Courier New',Courier,monospace; font-size: 15px; background: #eef2f7; padding: 2px 6px; border-radius: 4px;\">errno<\/code> is the error number, <code style=\"font-family: 'Courier New',Courier,monospace; font-size: 15px; background: #eef2f7; padding: 2px 6px; border-radius: 4px;\">strerror<\/code> is the message, and <code style=\"font-family: 'Courier New',Courier,monospace; font-size: 15px; background: #eef2f7; padding: 2px 6px; border-radius: 4px;\">filename<\/code> is the file that caused it.<\/p>\n<div style=\"margin: 20px 0; border: 1px solid #d9e0ea; border-radius: 8px; overflow: hidden;\">\n<div style=\"background: #0f2a4a; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">python<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #f5f8fc;\">try:\r\n    infile = open(\"Incorrect filename\")\r\nexcept OSError as ioe:\r\n    print(\"Unable to open the file\")\r\n    print(\"Error number\", ioe.errno)\r\n    print(\"Message\", ioe.strerror)\r\n    print(\"Filename in error\", ioe.filename)<\/pre>\n<div style=\"background: #1f2937; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">output<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #ffffff;\">Unable to open the file\r\nError number 2\r\nMessage No such file or directory\r\nFilename in error Incorrect filename<\/pre>\n<\/div>\n<h3 style=\"font-family: Arial,Helvetica,sans-serif; font-size: 21px; line-height: 1.35; font-weight: bold; color: #0f2a4a; margin: 28px 0 10px;\">Use with to Close Files Safely<\/h3>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">The <code style=\"font-family: 'Courier New',Courier,monospace; font-size: 15px; background: #eef2f7; padding: 2px 6px; border-radius: 4px;\">with<\/code> statement closes the file for you, even when an error happens, so you do not need a finally block just for that.<\/p>\n<div style=\"margin: 20px 0; border: 1px solid #d9e0ea; border-radius: 8px; overflow: hidden;\">\n<div style=\"background: #0f2a4a; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">python<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #f5f8fc;\">try:\r\n    with open(\"notes_missing.txt\") as f:\r\n        data = f.read()\r\nexcept FileNotFoundError:\r\n    print(\"File not found, using default text\")<\/pre>\n<div style=\"background: #1f2937; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">output<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #ffffff;\">File not found, using default text<\/pre>\n<\/div>\n<div style=\"position: relative; width: 100%; max-width: 850px; margin: 20px auto; padding-bottom: min(56.25%,478px); height: 0; overflow: hidden; border-radius: 8px;\"><iframe style=\"position: absolute; top: 0; left: 0; width: 100%; height: 100%; border: 0;\" title=\"Python exception handling video\" src=\"https:\/\/www.youtube.com\/embed\/j-UnQNn07LA\" allowfullscreen=\"allowfullscreen\"><\/iframe><\/div>\n<h2 style=\"font-family: Arial,Helvetica,sans-serif; font-size: 26px; line-height: 1.3; font-weight: bold; color: #0f2a4a; margin: 36px 0 12px;\">The Exception Hierarchy<\/h2>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">Exceptions are arranged in a family tree. Every exception inherits from <code style=\"font-family: 'Courier New',Courier,monospace; font-size: 15px; background: #eef2f7; padding: 2px 6px; border-radius: 4px;\">BaseException<\/code>. Almost all the errors you meet inherit from <code style=\"font-family: 'Courier New',Courier,monospace; font-size: 15px; background: #eef2f7; padding: 2px 6px; border-radius: 4px;\">Exception<\/code>, which sits just below it. So <code style=\"font-family: 'Courier New',Courier,monospace; font-size: 15px; background: #eef2f7; padding: 2px 6px; border-radius: 4px;\">Exception<\/code> is not the top of the tree.<\/p>\n<div style=\"margin: 20px 0; border: 1px solid #d9e0ea; border-radius: 8px; overflow: hidden;\">\n<div style=\"background: #0f2a4a; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">python<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #f5f8fc;\">print(ZeroDivisionError.__mro__)\r\nprint(issubclass(KeyError, LookupError), issubclass(IndexError, LookupError))<\/pre>\n<div style=\"background: #1f2937; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">output<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #ffffff;\">(&lt;class 'ZeroDivisionError'&gt;, &lt;class 'ArithmeticError'&gt;, &lt;class 'Exception'&gt;, &lt;class 'BaseException'&gt;, &lt;class 'object'&gt;)\r\nTrue True<\/pre>\n<\/div>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">The first line reads from the left: ZeroDivisionError is a kind of ArithmeticError, which is a kind of Exception, which is a kind of BaseException. KeyError and IndexError are both kinds of LookupError. That means catching the parent catches all its children.<\/p>\n<h2 style=\"font-family: Arial,Helvetica,sans-serif; font-size: 26px; line-height: 1.3; font-weight: bold; color: #0f2a4a; margin: 36px 0 12px;\">Why the Order of except Blocks Matters<\/h2>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">Python runs the first except block that matches. If a parent comes before its child, the child block can never run.<\/p>\n<div style=\"margin: 20px 0; border: 1px solid #d9e0ea; border-radius: 8px; overflow: hidden;\">\n<div style=\"background: #0f2a4a; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">python<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #f5f8fc;\">try:\r\n    [1, 2][5]\r\nexcept LookupError:\r\n    print(\"Caught by the parent first\")\r\nexcept IndexError:\r\n    print(\"Never reached\")<\/pre>\n<div style=\"background: #1f2937; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">output<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #ffffff;\">Caught by the parent first<\/pre>\n<\/div>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">Put the most specific exception first, and the general ones after.<\/p>\n<h2 style=\"font-family: Arial,Helvetica,sans-serif; font-size: 26px; line-height: 1.3; font-weight: bold; color: #0f2a4a; margin: 36px 0 12px;\">Best Practices and Common Mistakes<\/h2>\n<ul style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px; padding-left: 24px;\">\n<li style=\"margin: 0 0 8px;\"><strong>Do not use a bare except.<\/strong> An except line with no type catches everything, even a user pressing Ctrl and C, and hides real bugs. Name the errors you expect.<\/li>\n<li style=\"margin: 0 0 8px;\"><strong>Keep the try block small.<\/strong> Put only the risky lines inside it, so you know which line failed.<\/li>\n<li style=\"margin: 0 0 8px;\"><strong>Do not silence errors.<\/strong> An empty except block with only <code style=\"font-family: 'Courier New',Courier,monospace; font-size: 15px; background: #eef2f7; padding: 2px 6px; border-radius: 4px;\">pass<\/code> makes bugs invisible. At least print or log the message.<\/li>\n<li style=\"margin: 0 0 8px;\"><strong>Catch the specific error.<\/strong> Use <code style=\"font-family: 'Courier New',Courier,monospace; font-size: 15px; background: #eef2f7; padding: 2px 6px; border-radius: 4px;\">ValueError<\/code> for bad input and <code style=\"font-family: 'Courier New',Courier,monospace; font-size: 15px; background: #eef2f7; padding: 2px 6px; border-radius: 4px;\">FileNotFoundError<\/code> for a missing file, not the general <code style=\"font-family: 'Courier New',Courier,monospace; font-size: 15px; background: #eef2f7; padding: 2px 6px; border-radius: 4px;\">Exception<\/code>.<\/li>\n<li style=\"margin: 0 0 8px;\"><strong>Use finally or with for cleanup.<\/strong> Files and connections should close, even when something fails.<\/li>\n<li style=\"margin: 0 0 8px;\"><strong>Order the except blocks from specific to general.<\/strong><\/li>\n<li style=\"margin: 0 0 8px;\"><strong>Raise your own errors early.<\/strong> Check the input at the start of a function and raise a clear error, instead of letting it fail somewhere confusing.<\/li>\n<li style=\"margin: 0 0 8px;\"><strong>Watch the spelling and the colon.<\/strong> Writing <code style=\"font-family: 'Courier New',Courier,monospace; font-size: 15px; background: #eef2f7; padding: 2px 6px; border-radius: 4px;\">exceptValueError<\/code>, or leaving the colon off an except line, is a syntax error, and Python will not even start the program.<\/li>\n<\/ul>\n<h2 style=\"font-family: Arial,Helvetica,sans-serif; font-size: 26px; line-height: 1.3; font-weight: bold; color: #0f2a4a; margin: 36px 0 12px;\">Quick Reference<\/h2>\n<div style=\"border: 1px solid #d9e0ea; border-radius: 8px; overflow-x: auto; margin: 20px 0; -webkit-overflow-scrolling: touch;\">\n<table style=\"width: 100%; min-width: 560px; border-collapse: collapse; font-family: Arial,Helvetica,sans-serif; font-size: 16px; line-height: 1.6; color: #1f2937;\">\n<caption style=\"caption-side: top; text-align: left; padding: 14px 16px; font-weight: bold; font-size: 17px; color: #0f2a4a;\">Exception handling keywords<\/caption>\n<thead>\n<tr>\n<th style=\"background: #0f2a4a; color: #ffffff; text-align: left; padding: 12px 16px; border-bottom: 2px solid #0b1f38; width: 140px;\" scope=\"col\">Keyword<\/th>\n<th style=\"background: #0f2a4a; color: #ffffff; text-align: left; padding: 12px 16px; border-bottom: 2px solid #0b1f38;\" scope=\"col\">What it does<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr style=\"background: #ffffff;\">\n<th style=\"text-align: left; padding: 12px 16px; border-bottom: 1px solid #e5e9f0; color: #0f2a4a; font-family: 'Courier New',Courier,monospace; font-size: 15px; white-space: nowrap;\" scope=\"row\">try<\/th>\n<td style=\"padding: 12px 16px; border-bottom: 1px solid #e5e9f0;\">Holds the code that might fail<\/td>\n<\/tr>\n<tr style=\"background: #f5f8fc;\">\n<th style=\"text-align: left; padding: 12px 16px; border-bottom: 1px solid #e5e9f0; color: #0f2a4a; font-family: 'Courier New',Courier,monospace; font-size: 15px; white-space: nowrap;\" scope=\"row\">except<\/th>\n<td style=\"padding: 12px 16px; border-bottom: 1px solid #e5e9f0;\">Runs if a matching error happens, and can name the error type<\/td>\n<\/tr>\n<tr style=\"background: #ffffff;\">\n<th style=\"text-align: left; padding: 12px 16px; border-bottom: 1px solid #e5e9f0; color: #0f2a4a; font-family: 'Courier New',Courier,monospace; font-size: 15px; white-space: nowrap;\" scope=\"row\">else<\/th>\n<td style=\"padding: 12px 16px; border-bottom: 1px solid #e5e9f0;\">Runs only if the try block had no error<\/td>\n<\/tr>\n<tr style=\"background: #f5f8fc;\">\n<th style=\"text-align: left; padding: 12px 16px; border-bottom: 1px solid #e5e9f0; color: #0f2a4a; font-family: 'Courier New',Courier,monospace; font-size: 15px; white-space: nowrap;\" scope=\"row\">finally<\/th>\n<td style=\"padding: 12px 16px; border-bottom: 1px solid #e5e9f0;\">Always runs, used for cleanup<\/td>\n<\/tr>\n<tr style=\"background: #ffffff;\">\n<th style=\"text-align: left; padding: 12px 16px; border-bottom: 1px solid #e5e9f0; color: #0f2a4a; font-family: 'Courier New',Courier,monospace; font-size: 15px; white-space: nowrap;\" scope=\"row\">raise<\/th>\n<td style=\"padding: 12px 16px; border-bottom: 1px solid #e5e9f0;\">Raises an exception yourself, or raises the current one again<\/td>\n<\/tr>\n<tr style=\"background: #f5f8fc;\">\n<th style=\"text-align: left; padding: 12px 16px; color: #0f2a4a; font-family: 'Courier New',Courier,monospace; font-size: 15px; white-space: nowrap;\" scope=\"row\">as<\/th>\n<td style=\"padding: 12px 16px;\">Gives a name to the error object, such as except ValueError as e<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/div>\n<h2 style=\"font-family: Arial,Helvetica,sans-serif; font-size: 26px; line-height: 1.3; font-weight: bold; color: #0f2a4a; margin: 36px 0 12px;\">Complete Script to Run Yourself<\/h2>\n<p style=\"font-family: Arial,Helvetica,sans-serif; font-size: 17px; line-height: 1.7; color: #1f2937; margin: 0 0 16px;\">Here is the full script used to produce every output on this page. Copy it into a file, run it with Python 3, and compare the results line by line.<\/p>\n<div style=\"margin: 20px 0; border: 1px solid #d9e0ea; border-radius: 8px; overflow: hidden;\">\n<div style=\"background: #0f2a4a; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">python<\/div>\n<pre style=\"margin: 0; padding: 16px; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre; background: #f5f8fc;\"># 1. The basic try and except\r\ntest = [1, 2, 4, 8]\r\ntry:\r\n    print(\"First element = %d\" % (test[0]))\r\n    # Only 4 elements, so index 4 raises an IndexError\r\n    print(\"Fifth element = %d\" % (test[4]))\r\nexcept IndexError:\r\n    print(\"Error occurred\")\r\n \r\n# 2. What an unhandled error looks like (we catch it only to show the message)\r\nfor label, func in [\r\n    (\"ZeroDivisionError\", lambda: 10 \/ 0),\r\n    (\"NameError\", lambda: undefined_name),\r\n    (\"IndexError\", lambda: [1, 2, 3][5]),\r\n    (\"KeyError\", lambda: {\"a\": 1}[\"b\"]),\r\n    (\"ValueError\", lambda: int(\"abc\")),\r\n    (\"TypeError\", lambda: \"5\" + 5),\r\n    (\"FileNotFoundError\", lambda: open(\"no_such_file.txt\")),\r\n]:\r\n    try:\r\n        func()\r\n    except Exception as e:\r\n        print(label, \"-&gt;\", e)\r\n \r\n# 3. Handling several exceptions\r\ndef calculate(vari):\r\n    try:\r\n        cal = 100 \/ (vari - 5)\r\n        print(\"value of cal =\", cal)\r\n    except (ZeroDivisionError, TypeError):\r\n        print(\"Error handled\")\r\n \r\ncalculate(5)\r\ncalculate(7)\r\ncalculate(\"seven\")\r\n \r\n# 4. Separate handlers for separate errors\r\ndef divide(a, b):\r\n    try:\r\n        result = a \/ b\r\n    except ZeroDivisionError:\r\n        print(\"You cannot divide by zero\")\r\n    except TypeError:\r\n        print(\"Both values must be numbers\")\r\n    else:\r\n        print(\"Result:\", result)\r\n    finally:\r\n        print(\"Division attempted\")\r\n \r\ndivide(10, 2)\r\ndivide(10, 0)\r\ndivide(10, \"2\")\r\n \r\n# 5. else and finally\r\ndef print_age_in_days(years):\r\n    print(\"Your age in days is about\", 365 * int(years))\r\n \r\ndef check_age(age):\r\n    try:\r\n        print_age_in_days(age)\r\n    except ValueError:\r\n        print(\"You did not enter an age as a whole number\")\r\n    else:\r\n        print(age, \"successfully converted into days\")\r\n    finally:\r\n        print(\"Input test complete\")\r\n \r\ncheck_age(\"20\")\r\ncheck_age(\"20.5\")\r\n \r\n# 6. The raise statement\r\ntry:\r\n    raise NameError(\"Python code\")\r\nexcept NameError as e:\r\n    print(\"Exception:\", e)\r\n \r\n# 7. Raising again with a bare raise, caught by an outer handler\r\ntry:\r\n    try:\r\n        raise NameError(\"Python code\")\r\n    except NameError:\r\n        print(\"Inner handler ran\")\r\n        raise\r\nexcept NameError as e:\r\n    print(\"Outer handler caught:\", e)\r\n \r\n# 8. Raising your own error with a check\r\ndef set_age(age):\r\n    if age &lt; 0:\r\n        raise ValueError(\"Age cannot be negative\")\r\n    return age\r\n \r\ntry:\r\n    set_age(-5)\r\nexcept ValueError as e:\r\n    print(\"Error:\", e)\r\n \r\n# 9. Custom exception\r\nclass LowBalanceError(Exception):\r\n    pass\r\n \r\ndef withdraw(balance, amount):\r\n    if amount &gt; balance:\r\n        raise LowBalanceError(f\"Balance {balance} is less than {amount}\")\r\n    return balance - amount\r\n \r\ntry:\r\n    withdraw(500, 800)\r\nexcept LowBalanceError as e:\r\n    print(\"Custom error:\", e)\r\n \r\n# 10. Opening files\r\ntry:\r\n    infile = open(\"Incorrect filename\")\r\nexcept OSError as ioe:\r\n    print(\"Unable to open the file\")\r\n    print(\"Error number\", ioe.errno)\r\n    print(\"Message\", ioe.strerror)\r\n    print(\"Filename in error\", ioe.filename)\r\n \r\nprint(IOError is OSError)\r\nprint(FileNotFoundError.__mro__[1].__name__)\r\n \r\n# 11. with closes the file for you\r\ntry:\r\n    with open(\"notes_missing.txt\") as f:\r\n        data = f.read()\r\nexcept FileNotFoundError:\r\n    print(\"File not found, using default text\")\r\n \r\n# 12. The exception hierarchy\r\nprint(ZeroDivisionError.__mro__)\r\nprint(Exception.__mro__)\r\nprint(issubclass(KeyError, LookupError), issubclass(IndexError, LookupError))\r\n \r\n# 13. Order of except blocks matters\r\ntry:\r\n    [1, 2][5]\r\nexcept LookupError:\r\n    print(\"Caught by the parent first\")\r\nexcept IndexError:\r\n    print(\"Never reached\")\r\n \r\n# 14. Catching every error, and why not to\r\ntry:\r\n    int(\"abc\")\r\nexcept Exception as e:\r\n    print(type(e).__name__, \"-\", e)\r\n \r\n# 15. Getting the full traceback text\r\nimport traceback\r\ntry:\r\n    1 \/ 0\r\nexcept ZeroDivisionError:\r\n    print(traceback.format_exc().strip().splitlines()[-1])\r\n \r\n# 16. Syntax errors are not caught at run time\r\ntry:\r\n    compile(\"print('hello'\", \"&lt;test&gt;\", \"exec\")\r\nexcept SyntaxError as e:\r\n    print(\"SyntaxError:\", e.msg)<\/pre>\n<\/div>\n<p>Exception handling is less about stopping errors and more about deciding what happens next. Catch the specific errors you expect, give the user a clear message, clean up with finally or with, and raise your own errors when the data is wrong. Run the script above, break each example on purpose, and read the messages. Then move on to Python file handling and modules, where these habits are used all the time.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Python Exception Handling Tutorial: try, except, else and finally A program that works on your own test data can still break the moment a real user touches it. Someone types a word where you expected a number. A file is missing. A network call times out. A list is shorter than you thought. Without any [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[28,1677],"tags":[531,399,532],"class_list":["post-2654","post","type-post","status-publish","format-standard","hentry","category-python","category-python-exception-handling","tag-best-python-training-in-btm-layout","tag-python-exception-handling-tutorial","tag-python-training-in-btm"],"acf":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v25.7 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Python Exception Handling: try, except, else, finally | PrwaTech<\/title>\n<meta name=\"description\" content=\"Learn Python exception handling with tested examples: try, except, else, finally, raise, custom exceptions, file errors and the exception hierarchy.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/prwatech.in\/blog\/python\/python-exception-handling\/python-exception-handling-tutorial\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Python Exception Handling: try, except, else, finally | PrwaTech\" \/>\n<meta property=\"og:description\" content=\"Learn Python exception handling with tested examples: try, except, else, finally, raise, custom exceptions, file errors and the exception hierarchy.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/prwatech.in\/blog\/python\/python-exception-handling\/python-exception-handling-tutorial\/\" \/>\n<meta property=\"og:site_name\" content=\"Prwatech\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/prwatech.in\/\" \/>\n<meta property=\"article:published_time\" content=\"2026-10-19T11:00:23+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2026-10-20T06:21:17+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/prwatech.in\/blog\/wp-content\/uploads\/2019\/07\/Untitled-design-1-1024x576.png\" \/>\n<meta name=\"author\" content=\"Prwatech\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@Eduprwatech\" \/>\n<meta name=\"twitter:site\" content=\"@Eduprwatech\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Prwatech\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"8 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\/\/prwatech.in\/blog\/python\/python-exception-handling\/python-exception-handling-tutorial\/\",\"url\":\"https:\/\/prwatech.in\/blog\/python\/python-exception-handling\/python-exception-handling-tutorial\/\",\"name\":\"Python Exception Handling: try, except, else, finally | PrwaTech\",\"isPartOf\":{\"@id\":\"https:\/\/prwatech.in\/blog\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/prwatech.in\/blog\/python\/python-exception-handling\/python-exception-handling-tutorial\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/prwatech.in\/blog\/python\/python-exception-handling\/python-exception-handling-tutorial\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/prwatech.in\/blog\/wp-content\/uploads\/2019\/07\/Untitled-design-1-1024x576.png\",\"datePublished\":\"2026-10-19T11:00:23+00:00\",\"dateModified\":\"2026-10-20T06:21:17+00:00\",\"author\":{\"@id\":\"https:\/\/prwatech.in\/blog\/#\/schema\/person\/db90baff7744090b2288bbc98fea87f3\"},\"description\":\"Learn Python exception handling with tested examples: try, except, else, finally, raise, custom exceptions, file errors and the exception hierarchy.\",\"breadcrumb\":{\"@id\":\"https:\/\/prwatech.in\/blog\/python\/python-exception-handling\/python-exception-handling-tutorial\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/prwatech.in\/blog\/python\/python-exception-handling\/python-exception-handling-tutorial\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/prwatech.in\/blog\/python\/python-exception-handling\/python-exception-handling-tutorial\/#primaryimage\",\"url\":\"https:\/\/prwatech.in\/blog\/wp-content\/uploads\/2019\/07\/Untitled-design-1.png\",\"contentUrl\":\"https:\/\/prwatech.in\/blog\/wp-content\/uploads\/2019\/07\/Untitled-design-1.png\",\"width\":1280,\"height\":720},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/prwatech.in\/blog\/python\/python-exception-handling\/python-exception-handling-tutorial\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/prwatech.in\/blog\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Python Exception Handling Tutorial\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/prwatech.in\/blog\/#website\",\"url\":\"https:\/\/prwatech.in\/blog\/\",\"name\":\"Prwatech\",\"description\":\"Share Ideas, Start Something Good.\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/prwatech.in\/blog\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Person\",\"@id\":\"https:\/\/prwatech.in\/blog\/#\/schema\/person\/db90baff7744090b2288bbc98fea87f3\",\"name\":\"Prwatech\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/prwatech.in\/blog\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/c00bafc1b04045f31eda917de39891456c44fa47c092b9bb6be0f860a3a30a2f?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/c00bafc1b04045f31eda917de39891456c44fa47c092b9bb6be0f860a3a30a2f?s=96&d=mm&r=g\",\"caption\":\"Prwatech\"},\"url\":\"https:\/\/prwatech.in\/blog\/author\/prwatech123\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Python Exception Handling: try, except, else, finally | PrwaTech","description":"Learn Python exception handling with tested examples: try, except, else, finally, raise, custom exceptions, file errors and the exception hierarchy.","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:\/\/prwatech.in\/blog\/python\/python-exception-handling\/python-exception-handling-tutorial\/","og_locale":"en_US","og_type":"article","og_title":"Python Exception Handling: try, except, else, finally | PrwaTech","og_description":"Learn Python exception handling with tested examples: try, except, else, finally, raise, custom exceptions, file errors and the exception hierarchy.","og_url":"https:\/\/prwatech.in\/blog\/python\/python-exception-handling\/python-exception-handling-tutorial\/","og_site_name":"Prwatech","article_publisher":"https:\/\/www.facebook.com\/prwatech.in\/","article_published_time":"2026-10-19T11:00:23+00:00","article_modified_time":"2026-10-20T06:21:17+00:00","og_image":[{"url":"https:\/\/prwatech.in\/blog\/wp-content\/uploads\/2019\/07\/Untitled-design-1-1024x576.png","type":"","width":"","height":""}],"author":"Prwatech","twitter_card":"summary_large_image","twitter_creator":"@Eduprwatech","twitter_site":"@Eduprwatech","twitter_misc":{"Written by":"Prwatech","Est. reading time":"8 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/prwatech.in\/blog\/python\/python-exception-handling\/python-exception-handling-tutorial\/","url":"https:\/\/prwatech.in\/blog\/python\/python-exception-handling\/python-exception-handling-tutorial\/","name":"Python Exception Handling: try, except, else, finally | PrwaTech","isPartOf":{"@id":"https:\/\/prwatech.in\/blog\/#website"},"primaryImageOfPage":{"@id":"https:\/\/prwatech.in\/blog\/python\/python-exception-handling\/python-exception-handling-tutorial\/#primaryimage"},"image":{"@id":"https:\/\/prwatech.in\/blog\/python\/python-exception-handling\/python-exception-handling-tutorial\/#primaryimage"},"thumbnailUrl":"https:\/\/prwatech.in\/blog\/wp-content\/uploads\/2019\/07\/Untitled-design-1-1024x576.png","datePublished":"2026-10-19T11:00:23+00:00","dateModified":"2026-10-20T06:21:17+00:00","author":{"@id":"https:\/\/prwatech.in\/blog\/#\/schema\/person\/db90baff7744090b2288bbc98fea87f3"},"description":"Learn Python exception handling with tested examples: try, except, else, finally, raise, custom exceptions, file errors and the exception hierarchy.","breadcrumb":{"@id":"https:\/\/prwatech.in\/blog\/python\/python-exception-handling\/python-exception-handling-tutorial\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/prwatech.in\/blog\/python\/python-exception-handling\/python-exception-handling-tutorial\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/prwatech.in\/blog\/python\/python-exception-handling\/python-exception-handling-tutorial\/#primaryimage","url":"https:\/\/prwatech.in\/blog\/wp-content\/uploads\/2019\/07\/Untitled-design-1.png","contentUrl":"https:\/\/prwatech.in\/blog\/wp-content\/uploads\/2019\/07\/Untitled-design-1.png","width":1280,"height":720},{"@type":"BreadcrumbList","@id":"https:\/\/prwatech.in\/blog\/python\/python-exception-handling\/python-exception-handling-tutorial\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/prwatech.in\/blog\/"},{"@type":"ListItem","position":2,"name":"Python Exception Handling Tutorial"}]},{"@type":"WebSite","@id":"https:\/\/prwatech.in\/blog\/#website","url":"https:\/\/prwatech.in\/blog\/","name":"Prwatech","description":"Share Ideas, Start Something Good.","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/prwatech.in\/blog\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Person","@id":"https:\/\/prwatech.in\/blog\/#\/schema\/person\/db90baff7744090b2288bbc98fea87f3","name":"Prwatech","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/prwatech.in\/blog\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/c00bafc1b04045f31eda917de39891456c44fa47c092b9bb6be0f860a3a30a2f?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/c00bafc1b04045f31eda917de39891456c44fa47c092b9bb6be0f860a3a30a2f?s=96&d=mm&r=g","caption":"Prwatech"},"url":"https:\/\/prwatech.in\/blog\/author\/prwatech123\/"}]}},"_links":{"self":[{"href":"https:\/\/prwatech.in\/blog\/wp-json\/wp\/v2\/posts\/2654","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/prwatech.in\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/prwatech.in\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/prwatech.in\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/prwatech.in\/blog\/wp-json\/wp\/v2\/comments?post=2654"}],"version-history":[{"count":11,"href":"https:\/\/prwatech.in\/blog\/wp-json\/wp\/v2\/posts\/2654\/revisions"}],"predecessor-version":[{"id":12052,"href":"https:\/\/prwatech.in\/blog\/wp-json\/wp\/v2\/posts\/2654\/revisions\/12052"}],"wp:attachment":[{"href":"https:\/\/prwatech.in\/blog\/wp-json\/wp\/v2\/media?parent=2654"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/prwatech.in\/blog\/wp-json\/wp\/v2\/categories?post=2654"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/prwatech.in\/blog\/wp-json\/wp\/v2\/tags?post=2654"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}