﻿{"id":988,"date":"2015-03-21T21:38:00","date_gmt":"2015-03-21T13:38:00","guid":{"rendered":"http:\/\/zerobox.org\/notes\/?p=988"},"modified":"2016-06-02T19:36:53","modified_gmt":"2016-06-02T11:36:53","slug":"python%e5%bc%82%e5%b8%b8%e5%a4%84%e7%90%86","status":"publish","type":"post","link":"http:\/\/zerobox.org\/notes\/988.html","title":{"rendered":"Python\u5f02\u5e38\u5904\u7406"},"content":{"rendered":"<h3>8.1. Syntax Errors<\/h3>\n<p>Syntax errors, also known as parsing errors, are perhaps the most common kind of complaint you get while you are still learning Python:<\/p>\n<p>\u8bed\u6cd5\u9519\u8bef\uff0c\u540c\u6837\u4e5f\u79f0\u4e3a\u53e5\u6cd5\u5206\u6790\u9519\u8bef\uff0c\u5f53\u4f60\u6b63\u5728\u5b66\u4e60Python\u7684\u8fc7\u7a0b\u4e2d\uff0c\u53ef\u80fd\u662f\u4f60\u62b1\u6028\u6700\u591a\u7684\u95ee\u9898\u3002<\/p>\n<div class=\"cnblogs_code\">\n<pre>&gt;&gt;&gt; while True print('Hello world')\r\n  File \"&lt;stdin&gt;\", line 1, in ?\r\n    while True print('Hello world')\r\n                   ^\r\nSyntaxError: invalid syntax<\/pre>\n<\/div>\n<p>The parser repeats the offending line and displays a little \u2018arrow\u2019 pointing at the earliest point in the line where the error was detected. The error is caused by (or at least detected at) the token <em>preceding<\/em> the arrow: in the example, the error is detected at the function <a class=\"reference internal\" title=\"print\" href=\"https:\/\/docs.python.org\/3.5\/library\/functions.html#print\"><tt class=\"xref py py-func docutils literal\"><span class=\"pre\">print()<\/span><\/tt><\/a>, since a colon (<tt class=\"docutils literal\"><span class=\"pre\">':'<\/span><\/tt>) is missing before it. File name and line number are printed so you know where to look in case the input came from a script.<\/p>\n<p>\u8bed\u6cd5\u5206\u6790\u5668\u4f1a\u91cd\u5199\u51fa\u9519\u7684\u8bed\u53e5\uff0c\u5e76\u7528\u4e00\u4e2a\u5411\u4e0a\u7684\u7bad\u5934\u6307\u5411\u9519\u8bef\u88ab\u68c0\u67e5\u5230\u7684\u5730\u65b9\u3002\u5728\u8fd9\u4e2a\u4f8b\u5b50\u4e2d\uff0c\u9519\u8bef\u662f\u7531\u4e8e\u5728print()\u51fd\u6570\u524d\u7f3a\u5c11\u5192\u53f7\uff1a\u9020\u6210\u7684\u3002\u6587\u4ef6\u540d\u548c\u884c\u53f7\u4e5f\u6253\u5370\u51fa\u6765\uff0c\u56e0\u6b64\u4f60\u53ef\u4ee5\u5c06\u9519\u8bef\u8f93\u51fa\u5230\u4e00\u4e2a\u811a\u672c\u4e2d\uff0c\u65b9\u4fbf\u5b9a\u4f4d\u95ee\u9898\u3002<\/p>\n<h3>8.2. Exceptions<\/h3>\n<p>Even if a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute it. Errors detected during execution are called <em>exceptions<\/em> and are not unconditionally fatal: you will soon learn how to handle them in Python programs. Most exceptions are not handled by programs, however, and result in error messages as shown here:<\/p>\n<p>\u5373\u4f7f\u8bed\u53e5\u6216\u8005\u8868\u8fbe\u5f0f\u5728\u8bed\u6cd5\u4e0a\u662f\u6b63\u786e\u7684\uff0c\u6267\u884c\u7684\u65f6\u5019\u4e5f\u53ef\u80fd\u51fa\u9519\u3002\u5728\u7a0b\u5e8f\u8fd0\u884c\u671f\u95f4\u51fa\u73b0\u81f4\u547d\u9519\u8bef\u6216\u8005\u7a0b\u5e8f\u8c03\u7528\u5f02\u5e38\u65f6\u4f1a\u8fdb\u884c\u9519\u8bef\u68c0\u6d4b\uff1a\u4f60\u5c06\u4f1a\u5b66\u4e60\u5230\u5728Python\u7a0b\u5e8f\u4e2d\u5982\u4f55\u5904\u7406\u5b83\u4eec\u3002\u8bb8\u591a\u5f02\u5e38\u7a0b\u5e8f\u662f\u4e0d\u4f1a\u624b\u52a8\u5904\u7406\u7684\uff1a<\/p>\n<div class=\"cnblogs_code\">\n<div class=\"cnblogs_code_toolbar\"><span class=\"cnblogs_code_copy\"><a title=\"\u590d\u5236\u4ee3\u7801\"><img decoding=\"async\" src=\"http:\/\/zerobox.org\/notes\/wp-content\/uploads\/2015\/03\/9148256b89e79e5d03bf03a93cf12ac4.gif\" alt=\"\u590d\u5236\u4ee3\u7801\" \/><\/a><\/span><\/div>\n<pre>&gt;&gt;&gt; 10 * (1\/0)\r\nTraceback (most recent call last):\r\n  File \"&lt;stdin&gt;\", line 1, in ?\r\nZeroDivisionError: division by zero\r\n&gt;&gt;&gt; 4 + spam*3\r\nTraceback (most recent call last):\r\n  File \"&lt;stdin&gt;\", line 1, in ?\r\nNameError: name 'spam' is not defined\r\n&gt;&gt;&gt; '2' + 2\r\nTraceback (most recent call last):\r\n  File \"&lt;stdin&gt;\", line 1, in ?\r\nTypeError: Can't convert 'int' object to str implicitly<\/pre>\n<div class=\"cnblogs_code_toolbar\"><span class=\"cnblogs_code_copy\"><a title=\"\u590d\u5236\u4ee3\u7801\"><img decoding=\"async\" src=\"http:\/\/zerobox.org\/notes\/wp-content\/uploads\/2015\/03\/9148256b89e79e5d03bf03a93cf12ac4.gif\" alt=\"\u590d\u5236\u4ee3\u7801\" \/><\/a><\/span><\/div>\n<\/div>\n<p>The last line of the error message indicates what happened. Exceptions come in different types, and the type is printed as part of the message: the types in the example are <a class=\"reference internal\" title=\"ZeroDivisionError\" href=\"https:\/\/docs.python.org\/3.5\/library\/exceptions.html#ZeroDivisionError\"><tt class=\"xref py py-exc docutils literal\"><span class=\"pre\">ZeroDivisionError<\/span><\/tt><\/a>, <a class=\"reference internal\" title=\"NameError\" href=\"https:\/\/docs.python.org\/3.5\/library\/exceptions.html#NameError\"><tt class=\"xref py py-exc docutils literal\"><span class=\"pre\">NameError<\/span><\/tt><\/a> and <a class=\"reference internal\" title=\"TypeError\" href=\"https:\/\/docs.python.org\/3.5\/library\/exceptions.html#TypeError\"><tt class=\"xref py py-exc docutils literal\"><span class=\"pre\">TypeError<\/span><\/tt><\/a>. The string printed as the exception type is the name of the built-in exception that occurred. This is true for all built-in exceptions, but need not be true for user-defined exceptions (although it is a useful convention). Standard exception names are built-in identifiers (not reserved keywords).<\/p>\n<p>\u9519\u8bef\u6d88\u606f\u7684\u6700\u540e\u4e00\u884c\u663e\u793a\u53d1\u751f\u4e86\u4ec0\u4e48\u60c5\u51b5\u3002\u5f02\u5e38\u6709\u5f88\u591a\u7c7b\u578b\uff0c\u5e76\u4f5c\u4e3a\u6d88\u606f\u7684\u4e00\u90e8\u5206\u6253\u5370\u51fa\u6765\uff1a\u5728\u8fd9\u4e2a\u4f8b\u5b50\u4e2d\uff0c\u5f02\u5e38\u7c7b\u578b\u6709ZeroDivisionError,NameError\u548cTypeError\u3002\u8fd9\u4e9b\u5f02\u5e38\u540d\u5b57\u662fPython\u5185\u7f6e\u7684\u3002\u7528\u6237\u4e5f\u53ef\u4ee5\u81ea\u5b9a\u4e49\u5f02\u5e38\u7c7b\u578b\u3002<\/p>\n<p>The rest of the line provides detail based on the type of exception and what caused it.<\/p>\n<p>\u9519\u8bef\u6d88\u606f\u7684\u5176\u4ed6\u90e8\u5206\u63d0\u4f9b\u4e86\u5f15\u53d1\u5f02\u5e38\u7684\u7ec6\u8282\u60c5\u51b5\u3002<\/p>\n<p>The preceding part of the error message shows the context where the exception happened, in the form of a stack traceback. In general it contains a stack traceback listing source lines; however, it will not display lines read from standard input.<\/p>\n<p>\u9519\u8bef\u6d88\u606f\u7684\u524d\u9762\u5e94\u8be5\u4f1a\u6307\u660e\u5f02\u5e38\u53d1\u751f\u7684\u4e0a\u4e0b\u6587\uff0c\u4f8b\u5982\u6307\u51fa\u5806\u6808\u4fe1\u606f\u3002\u4e00\u822c\u60c5\u51b5\u4e0b\uff0c\u5b83\u5e94\u8be5\u5305\u542b\u6e90\u7801\u7ea7\u522b\u7684\u5806\u6808\u4fe1\u606f\uff1b\u4f46\u662f\u4e0a\u9762\u7684\u4f8b\u5b50\u662f\u4ece\u6807\u51c6\u8f93\u5165\u8bbe\u5907\u4e2d\u8bfb\u53d6\u7684\u4ee3\u7801\uff0c\u56e0\u6b64\u6ca1\u6709\u663e\u793a\u5806\u6808\u4fe1\u606f\u3002<\/p>\n<h3>8.3. Handling Exceptions<\/h3>\n<p>It is possible to write programs that handle selected exceptions. Look at the following example, which asks the user for input until a valid integer has been entered, but allows the user to interrupt the program (using <tt class=\"kbd docutils literal\"><span class=\"pre\">Control-C<\/span><\/tt> or whatever the operating system supports); note that a user-generated interruption is signalled by raising the <a class=\"reference internal\" title=\"KeyboardInterrupt\" href=\"https:\/\/docs.python.org\/3.5\/library\/exceptions.html#KeyboardInterrupt\"><tt class=\"xref py py-exc docutils literal\"><span class=\"pre\">KeyboardInterrupt<\/span><\/tt><\/a> exception.<\/p>\n<p>\u5f53\u7136\uff0c\u6211\u4eec\u53ef\u4ee5\u5728\u7a0b\u5e8f\u4e2d\u9009\u62e9\u6027\u7684\u5904\u7406\u9700\u8981\u5904\u7406\u7684\u5f02\u5e38\u3002\u770b\u4e0b\u9762\u7684\u4f8b\u5b50\uff0c\u8bf7\u6c42\u7528\u6237\u7684\u8f93\u5165\u76f4\u5230\u8f93\u5165\u5408\u6cd5\u7684\u6574\u6570\u503c\uff0c\u4f46\u662f\u4e5f\u5141\u8bb8\u7528\u6237\u6253\u65ad\u7a0b\u5e8f\u7684\u8fd0\u884c(\u4f7f\u7528Control-C\u6216\u8005Control-Z)\uff1b\u6ce8\u610f\uff0c\u7528\u6237\u89e6\u53d1\u7684\u6253\u65ad\u5c06\u4f1a\u89e6\u53d1KeyboardInterrupt\u5f02\u5e38\u3002<\/p>\n<div class=\"cnblogs_code\">\n<div class=\"cnblogs_code_toolbar\"><span class=\"cnblogs_code_copy\"><a title=\"\u590d\u5236\u4ee3\u7801\"><img decoding=\"async\" src=\"http:\/\/zerobox.org\/notes\/wp-content\/uploads\/2015\/03\/9148256b89e79e5d03bf03a93cf12ac4.gif\" alt=\"\u590d\u5236\u4ee3\u7801\" \/><\/a><\/span><\/div>\n<pre>&gt;&gt;&gt; while True:\r\n...     try:\r\n...         x = int(input(\"Please enter a number: \"))\r\n...         break\r\n...     except ValueError:\r\n...         print(\"Oops!  That was no valid number.  Try again...\")\r\n...<\/pre>\n<div class=\"cnblogs_code_toolbar\"><span class=\"cnblogs_code_copy\"><a title=\"\u590d\u5236\u4ee3\u7801\"><img decoding=\"async\" src=\"http:\/\/zerobox.org\/notes\/wp-content\/uploads\/2015\/03\/9148256b89e79e5d03bf03a93cf12ac4.gif\" alt=\"\u590d\u5236\u4ee3\u7801\" \/><\/a><\/span><\/div>\n<\/div>\n<p>The <a class=\"reference internal\" href=\"https:\/\/docs.python.org\/3.5\/reference\/compound_stmts.html#try\"><tt class=\"xref std std-keyword docutils literal\"><span class=\"pre\">try<\/span><\/tt><\/a> statement works as follows.<\/p>\n<p>try\u8bed\u53e5\u5de5\u4f5c\u673a\u5236\uff1a<\/p>\n<ul class=\"simple\">\n<li>First, the <em>try clause<\/em> (the statement(s) between the <a class=\"reference internal\" href=\"https:\/\/docs.python.org\/3.5\/reference\/compound_stmts.html#try\"><tt class=\"xref std std-keyword docutils literal\"><span class=\"pre\">try<\/span><\/tt><\/a> and <a class=\"reference internal\" href=\"https:\/\/docs.python.org\/3.5\/reference\/compound_stmts.html#except\"><tt class=\"xref std std-keyword docutils literal\"><span class=\"pre\">except<\/span><\/tt><\/a> keywords) is executed.<\/li>\n<li>\u9996\u5148\uff0c\u6267\u884ctry\u548cexcept\u5173\u952e\u5b57\u4e4b\u95f4\u7684\u8bed\u53e5<\/li>\n<li>If no exception occurs, the <em>except clause<\/em> is skipped and execution of the <a class=\"reference internal\" href=\"https:\/\/docs.python.org\/3.5\/reference\/compound_stmts.html#try\"><tt class=\"xref std std-keyword docutils literal\"><span class=\"pre\">try<\/span><\/tt><\/a> statement is finished.<\/li>\n<li>\u5982\u679c\u6ca1\u6709\u5f02\u5e38\u53d1\u751f\uff0cexcept\u8bed\u53e5\u88ab\u5ffd\u7565\uff0ctry\u8bed\u53e5\u6267\u884c\u5b8c\u6bd5\u3002<\/li>\n<li>If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then if its type matches the exception named after the <a class=\"reference internal\" href=\"https:\/\/docs.python.org\/3.5\/reference\/compound_stmts.html#except\"><tt class=\"xref std std-keyword docutils literal\"><span class=\"pre\">except<\/span><\/tt><\/a> keyword, the except clause is executed, and then execution continues after the <a class=\"reference internal\" href=\"https:\/\/docs.python.org\/3.5\/reference\/compound_stmts.html#try\"><tt class=\"xref std std-keyword docutils literal\"><span class=\"pre\">try<\/span><\/tt><\/a> statement.<\/li>\n<li>\u5982\u679c\u5728try\u8bed\u53e5\u4e2d\u53d1\u751f\u5f02\u5e38\uff0c\u5219\u6253\u65adtry\u540e\u9762\u7684\u8bed\u53e5\u3002\u5982\u679c\u5f02\u5e38\u7684\u7c7b\u578b\u5339\u914dexcept\u540e\u9762\u7684\u7c7b\u578b\uff0c\u5219except\u8bed\u53e5\u5757\u88ab\u6267\u884c\u3002\u7136\u540e\u518d\u6267\u884ctry-except\u5757\u540e\u9762\u7684\u8bed\u53e5\u3002<\/li>\n<li>If an exception occurs which does not match the exception named in the except clause, it is passed on to outer <a class=\"reference internal\" href=\"https:\/\/docs.python.org\/3.5\/reference\/compound_stmts.html#try\"><tt class=\"xref std std-keyword docutils literal\"><span class=\"pre\">try<\/span><\/tt><\/a> statements; if no handler is found, it is an <em>unhandled exception<\/em> and execution stops with a message as shown above.<\/li>\n<li>\u5982\u679c\u53d1\u751f\u7684\u5f02\u5e38\u7c7b\u578b\u548cexcept\u540e\u9762\u7684\u5f02\u5e38\u7c7b\u578b\u4e0d\u5339\u914d\uff0c\u5219\u5f02\u5e38\u4f1a\u88ab\u4f20\u9012\u5230try\u8bed\u53e5\u7684\u5916\u9762\uff0c\u5982\u679c\u5916\u5c42\u4e5f\u6ca1\u6709\u51fa\u6765\u8be5\uff0c\u5219\u4f1a\u7ec8\u6b62\u7a0b\u5e8f\u7684\u8fd0\u884c\uff0c\u5e76\u8fd4\u56de\u9519\u8bef\u6d88\u606f\u3002<\/li>\n<\/ul>\n<p>A <a class=\"reference internal\" href=\"https:\/\/docs.python.org\/3.5\/reference\/compound_stmts.html#try\"><tt class=\"xref std std-keyword docutils literal\"><span class=\"pre\">try<\/span><\/tt><\/a> statement may have more than one except clause, to specify handlers for different exceptions. At most one handler will be executed. Handlers only handle exceptions that occur in the corresponding try clause, not in other handlers of the same <a class=\"reference internal\" href=\"https:\/\/docs.python.org\/3.5\/reference\/compound_stmts.html#try\"><tt class=\"xref std std-keyword docutils literal\"><span class=\"pre\">try<\/span><\/tt><\/a> statement. An except clause may name multiple exceptions as a parenthesized tuple, for example:<\/p>\n<p>\u4e00\u4e2atry\u8bed\u53e5\u6709\u53ef\u80fd\u4e0d\u6b62\u4e00\u4e2aexcept\u8bed\u53e5\u5757\uff0c\u53ef\u4ee5\u4e3a\u4e0d\u540c\u7684\u5f02\u5e38\u6307\u5b9a\u5904\u7406\u7a0b\u5e8f\u3002\u4f46\u81f3\u591a\u53ea\u6709\u4e00\u4e2a\u5904\u7406\u7a0b\u5e8f\u4f1a\u6267\u884c\u3002\u5904\u7406\u7a0b\u5e8f\u4ec5\u4ec5\u53ea\u5904\u7406try\u8bed\u53e5\u4e2d\u76f8\u5e94\u7684\u5f02\u5e38\u7c7b\u578b\uff0c\u800c\u4e0d\u4f1a\u5904\u7406\u540c\u4e00\u4e2atry\u8bed\u53e5\u7684\u5176\u4ed6\u5f02\u5e38\u3002\u4e00\u4e2aexcept\u8bed\u53e5\u5757\u53ef\u4ee5\u5305\u542b\u591a\u4e2a\u5f02\u5e38\u7c7b\u578b\uff0c\u4f8b\u5982\uff1a<\/p>\n<div class=\"cnblogs_code\">\n<pre>... except (RuntimeError, TypeError, NameError):\r\n...     pass<\/pre>\n<\/div>\n<p>The last except clause may omit the exception name(s), to serve as a wildcard. Use this with extreme caution, since it is easy to mask a real programming error in this way! It can also be used to print an error message and then re-raise the exception (allowing a caller to handle the exception as well):<\/p>\n<p>try-except\u7684\u6700\u540e\u4e00\u4e2aexcept\u8bed\u53e5\u5757\u53ef\u4ee5\u7701\u7565\u5f02\u5e38\u7684\u540d\u5b57\uff0c\u6765\u4f5c\u4e3a\u4e00\u4e2a\u901a\u914d\u7b26\u3002\u4f7f\u7528\u8fd9\u79cd\u5f02\u5e38\u5757\u8981\u975e\u5e38\u7684\u5c0f\u5fc3\uff0c\u56e0\u4e3a\u8fd9\u79cd\u65b9\u5f0f\u5f88\u5bb9\u6613\u63a9\u76d6\u7a0b\u5e8f\u771f\u5b9e\u7684\u9519\u8bef\uff01\u5b83\u4e5f\u80fd\u591f\u5148\u6253\u5370\u9519\u8bef\u6d88\u606f\uff0c\u5e76\u5f15\u53d1\u5f02\u5e38(\u5141\u8bb8\u8c03\u7528\u51fd\u6570\u6765\u5904\u7406\u5f02\u5e38)\u3002<\/p>\n<div class=\"cnblogs_code\">\n<div class=\"cnblogs_code_toolbar\"><span class=\"cnblogs_code_copy\"><a title=\"\u590d\u5236\u4ee3\u7801\"><img decoding=\"async\" src=\"http:\/\/zerobox.org\/notes\/wp-content\/uploads\/2015\/03\/9148256b89e79e5d03bf03a93cf12ac4.gif\" alt=\"\u590d\u5236\u4ee3\u7801\" \/><\/a><\/span><\/div>\n<pre>import sys\r\n\r\ntry:\r\n    f = open('myfile.txt')\r\n    s = f.readline()\r\n    i = int(s.strip())\r\nexcept OSError as err:\r\n    print(\"OS error: {0}\".format(err))\r\nexcept ValueError:\r\n    print(\"Could not convert data to an integer.\")\r\nexcept:\r\n    print(\"Unexpected error:\", sys.exc_info()[0])\r\n    raise<\/pre>\n<div class=\"cnblogs_code_toolbar\"><span class=\"cnblogs_code_copy\"><a title=\"\u590d\u5236\u4ee3\u7801\"><img decoding=\"async\" src=\"http:\/\/zerobox.org\/notes\/wp-content\/uploads\/2015\/03\/9148256b89e79e5d03bf03a93cf12ac4.gif\" alt=\"\u590d\u5236\u4ee3\u7801\" \/><\/a><\/span><\/div>\n<\/div>\n<p>The <a class=\"reference internal\" href=\"https:\/\/docs.python.org\/3.4\/reference\/compound_stmts.html#try\"><tt class=\"xref std std-keyword docutils literal\">try<\/tt><\/a> &#8230; <a class=\"reference internal\" href=\"https:\/\/docs.python.org\/3.4\/reference\/compound_stmts.html#except\"><tt class=\"xref std std-keyword docutils literal\">except<\/tt><\/a> statement has an optional <em>else clause<\/em>, which, when present, must follow all except clauses. It is useful for code that must be executed if the try clause does not raise an exception. For example:<\/p>\n<p>try&#8230;except\u8bed\u53e5\u6709\u4e2a\u53ef\u9009\u62e9\u7684else\u8bed\u53e5\u5757\uff0c\u5b83\u5fc5\u987b\u8ddf\u968f\u5728\u6240\u6709\u7684except\u8bed\u53e5\u5757\u4e4b\u540e\u3002\u5b83\u7684\u4f5c\u7528\u662f\uff0c\u5982\u679ctry\u8bed\u53e5\u5757\u6ca1\u6709\u5f15\u53d1\u5f02\u5e38\uff0c\u5219else\u4ee3\u7801\u5757\u5fc5\u987b\u6267\u884c\u3002<\/p>\n<div class=\"cnblogs_code\">\n<div class=\"cnblogs_code_toolbar\"><span class=\"cnblogs_code_copy\"><a title=\"\u590d\u5236\u4ee3\u7801\"><img decoding=\"async\" src=\"http:\/\/zerobox.org\/notes\/wp-content\/uploads\/2015\/03\/9148256b89e79e5d03bf03a93cf12ac4.gif\" alt=\"\u590d\u5236\u4ee3\u7801\" \/><\/a><\/span><\/div>\n<pre>for arg in sys.argv[1:]:\r\n    try:\r\n        f = open(arg, 'r')\r\n    except IOError:\r\n        print('cannot open', arg)\r\n    else:\r\n        print(arg, 'has', len(f.readlines()), 'lines')\r\n        f.close()<\/pre>\n<div class=\"cnblogs_code_toolbar\"><span class=\"cnblogs_code_copy\"><a title=\"\u590d\u5236\u4ee3\u7801\"><img decoding=\"async\" src=\"http:\/\/zerobox.org\/notes\/wp-content\/uploads\/2015\/03\/9148256b89e79e5d03bf03a93cf12ac4.gif\" alt=\"\u590d\u5236\u4ee3\u7801\" \/><\/a><\/span><\/div>\n<\/div>\n<p>The use of the <a class=\"reference internal\" href=\"https:\/\/docs.python.org\/3.4\/reference\/compound_stmts.html#else\"><tt class=\"xref std std-keyword docutils literal\">else<\/tt><\/a> clause is better than adding additional code to the <a class=\"reference internal\" href=\"https:\/\/docs.python.org\/3.4\/reference\/compound_stmts.html#try\"><tt class=\"xref std std-keyword docutils literal\">try<\/tt><\/a> clause because it avoids accidentally catching an exception that wasn\u2019t raised by the code being protected by the <a class=\"reference internal\" href=\"https:\/\/docs.python.org\/3.4\/reference\/compound_stmts.html#try\"><tt class=\"xref std std-keyword docutils literal\">try<\/tt><\/a> &#8230; <a class=\"reference internal\" href=\"https:\/\/docs.python.org\/3.4\/reference\/compound_stmts.html#except\"><tt class=\"xref std std-keyword docutils literal\">except<\/tt><\/a> statement.<\/p>\n<p>\u4f7f\u7528else\u8bed\u53e5\u5757\u8981\u6bd4\u5728try\u8bed\u53e5\u4e2d\u589e\u52a0\u989d\u5916\u7684\u8bed\u53e5\u66f4\u597d\uff0c\u56e0\u4e3a\u5b83\u907f\u514d\u4e86\u610f\u5916\u7684\u5f02\u5e38\u6355\u6349\uff0c\u8fd9\u8fd9\u4e2a\u5f02\u5e38\u53ef\u80fd\u5e76\u4e0d\u662ftry&#8230;excepty\u8bed\u53e5\u4e2d\u8981\u6355\u6349\u7684\u3002<\/p>\n<p>When an exception occurs, it may have an associated value, also known as the exception\u2019s <em>argument<\/em>. The presence and type of the argument depend on the exception type.<\/p>\n<p>\u5f53\u53d1\u751f\u5f02\u5e38\u65f6\uff0c\u5b83\u53ef\u80fd\u6709\u4e2a\u5173\u8054\u503c\uff0c\u4e5f\u53eb\u505a\u5f02\u5e38\u7684\u53c2\u6570\u3002\u8fd9\u4e2a\u53c2\u6570\u7684\u7c7b\u578b\u4ee5\u53ca\u662f\u5426\u6709\u8fd9\u4e2a\u53c2\u6570\u53d6\u51b3\u4e8e\u5f02\u5e38\u7c7b\u578b\u3002<\/p>\n<p>The except clause may specify a variable after the exception name. The variable is bound to an exception instance with the arguments stored in <tt class=\"docutils literal\">instance.args<\/tt>. For convenience, the exception instance defines <a class=\"reference internal\" title=\"object.__str__\" href=\"https:\/\/docs.python.org\/3.4\/reference\/datamodel.html#object.__str__\"><tt class=\"xref py py-meth docutils literal\">__str__()<\/tt><\/a> so the arguments can be printed directly without having to reference <tt class=\"docutils literal\">.args<\/tt>. One may also instantiate an exception first before raising it and add any attributes to it as desired.<\/p>\n<p>except\u8bed\u53e5\u5757\u53ef\u4ee5\u5728\u5f02\u5e38\u540d\u5b57\u7684\u540e\u9762\u6307\u5b9a\u4e00\u4e2a\u53d8\u91cf\u3002\u8fd9\u4e2a\u53d8\u91cf\u7ed1\u5b9a\u4e86\u8be5\u5f02\u5e38\u7684\u5b9e\u4f8b\uff0c\u5e76\u4e14\u5f02\u5e38\u7684\u53c2\u6570\u5b58\u50a8\u5728instance.args\u3002\u4e3a\u4e86\u65b9\u4fbf\uff0c\u5f02\u5e38\u5b9e\u4f8b\u5b9a\u4e49\u4e86\u4e00\u4e2a__str()__\u51fd\u6570\uff0c\u56e0\u6b64\u53c2\u6570\u53ef\u4ee5\u76f4\u63a5\u6253\u5370\u800c\u4e0d\u5fc5\u5f15\u7528.args\u3002\u53ef\u80fd\u6709\u4eba\u60f3\u5728\u629b\u51fa\u5f02\u5e38\u524d\u5148\u521d\u59cb\u5316\u5f02\u5e38\u5b9e\u4f8b\uff0c\u7ed9\u8be5\u5f02\u5e38\u589e\u52a0\u4e00\u4e9b\u6240\u671f\u671b\u7684\u5c5e\u6027\u3002<\/p>\n<div class=\"cnblogs_code\">\n<div class=\"cnblogs_code_toolbar\"><span class=\"cnblogs_code_copy\"><a title=\"\u590d\u5236\u4ee3\u7801\"><img decoding=\"async\" src=\"http:\/\/zerobox.org\/notes\/wp-content\/uploads\/2015\/03\/9148256b89e79e5d03bf03a93cf12ac4.gif\" alt=\"\u590d\u5236\u4ee3\u7801\" \/><\/a><\/span><\/div>\n<pre>&gt;&gt;&gt; try:\r\n...    raise Exception('spam', 'eggs')\r\n... except Exception as inst:\r\n...    print(type(inst))    # the exception instance\r\n...    print(inst.args)     # arguments stored in .args\r\n...    print(inst)          # __str__ allows args to be printed directly,\r\n...                         # but may be overridden in exception subclasses\r\n...    x, y = inst.args     # unpack args\r\n...    print('x =', x)\r\n...    print('y =', y)\r\n...\r\n&lt;class 'Exception'&gt;\r\n('spam', 'eggs')\r\n('spam', 'eggs')\r\nx = spam\r\ny = eggs<\/pre>\n<div class=\"cnblogs_code_toolbar\"><span class=\"cnblogs_code_copy\"><a title=\"\u590d\u5236\u4ee3\u7801\"><img decoding=\"async\" src=\"http:\/\/zerobox.org\/notes\/wp-content\/uploads\/2015\/03\/9148256b89e79e5d03bf03a93cf12ac4.gif\" alt=\"\u590d\u5236\u4ee3\u7801\" \/><\/a><\/span><\/div>\n<\/div>\n<p>&nbsp;<\/p>\n<p>If an exception has arguments, they are printed as the last part (\u2018detail\u2019) of the message for unhandled exceptions.<\/p>\n<p>\u5982\u679c\u4e00\u4e2a\u5f02\u5e38\u5e26\u6709\u53c2\u6570\uff0c\u8fd9\u4e2a\u5f02\u5e38\u5982\u679c\u6ca1\u6709\u88ab\u5904\u7406\uff0c\u90a3\u4e48\u5b83\u7684\u8fd9\u4e9b\u53c2\u6570\u4f1a\u5728\u9519\u8bef\u6d88\u606f\u7684\u6700\u540e\u9762\u6253\u5370\u51fa\u6765\u3002<\/p>\n<p>Exception handlers don\u2019t just handle exceptions if they occur immediately in the try clause, but also if they occur inside functions that are called (even indirectly) in the try clause. For example:<\/p>\n<p>\u5f02\u5e38\u5904\u7406\u7a0b\u5e8f\u4e0d\u4ec5\u4ec5\u53ea\u5904\u7406\u5728try\u8bed\u53e5\u5757\u4e2d\u51fa\u73b0\u7684\u5f02\u5e38\uff0c\u800c\u4e14\u8fd8\u53ef\u4ee5\u5904\u7406\u5728try\u8bed\u53e5\u4e2d\u6240\u5305\u62ec\u7684\u51fd\u6570\u5185\u90e8\u7684\u5f02\u5e38\u3002\u4f8b\u5982\uff1a<\/p>\n<div class=\"cnblogs_code\">\n<div class=\"cnblogs_code_toolbar\"><span class=\"cnblogs_code_copy\"><a title=\"\u590d\u5236\u4ee3\u7801\"><img decoding=\"async\" src=\"http:\/\/zerobox.org\/notes\/wp-content\/uploads\/2015\/03\/9148256b89e79e5d03bf03a93cf12ac4.gif\" alt=\"\u590d\u5236\u4ee3\u7801\" \/><\/a><\/span><\/div>\n<pre>&gt;&gt;&gt; def this_fails():\r\n...     x = 1\/0\r\n...\r\n&gt;&gt;&gt; try:\r\n...     this_fails()\r\n... except ZeroDivisionError as err:\r\n...     print('Handling run-time error:', err)\r\n...\r\nHandling run-time error: int division or modulo by zero<\/pre>\n<div class=\"cnblogs_code_toolbar\"><span class=\"cnblogs_code_copy\"><a title=\"\u590d\u5236\u4ee3\u7801\"><img decoding=\"async\" src=\"http:\/\/zerobox.org\/notes\/wp-content\/uploads\/2015\/03\/9148256b89e79e5d03bf03a93cf12ac4.gif\" alt=\"\u590d\u5236\u4ee3\u7801\" \/><\/a><\/span><\/div>\n<\/div>\n<h2>8.4. Raising Exceptions<\/h2>\n<p>The <a class=\"reference internal\" href=\"https:\/\/docs.python.org\/3.4\/reference\/simple_stmts.html#raise\"><tt class=\"xref std std-keyword docutils literal\">raise<\/tt><\/a> statement allows the programmer to force a specified exception to occur. For example:<\/p>\n<p>raise\u8bed\u53e5\u8fd0\u884c\u7a0b\u5e8f\u5458\u8feb\u4f7f\u6307\u5b9a\u7684\u5f02\u5e38\u53d1\u751f\u3002\u4f8b\u5982\uff1a<\/p>\n<div class=\"cnblogs_code\">\n<pre>&gt;&gt;&gt; raise NameError('HiThere')\r\nTraceback (most recent call last):\r\n  File \"&lt;stdin&gt;\", line 1, in ?\r\nNameError: HiThere<\/pre>\n<\/div>\n<p>The sole argument to <a class=\"reference internal\" href=\"https:\/\/docs.python.org\/3.4\/reference\/simple_stmts.html#raise\"><tt class=\"xref std std-keyword docutils literal\">raise<\/tt><\/a> indicates the exception to be raised. This must be either an exception instance or an exception class (a class that derives from <a class=\"reference internal\" title=\"Exception\" href=\"https:\/\/docs.python.org\/3.4\/library\/exceptions.html#Exception\"><tt class=\"xref py py-class docutils literal\">Exception<\/tt><\/a>).<\/p>\n<p>raise\u552f\u4e00\u7684\u53c2\u6570\u8868\u660e\u4e86\u4ec0\u4e48\u5f02\u5e38\u88ab\u629b\u51fa\u3002\u8fd9\u4e2a\u53c2\u6570\u5fc5\u987b\u662f\u5f02\u5e38\u5b9e\u4f8b\u6216\u8005\u662fException\u7c7b\u53ca\u5b50\u7c7b\u3002<\/p>\n<p>If you need to determine whether an exception was raised but don\u2019t intend to handle it, a simpler form of the <a class=\"reference internal\" href=\"https:\/\/docs.python.org\/3.4\/reference\/simple_stmts.html#raise\"><tt class=\"xref std std-keyword docutils literal\">raise<\/tt><\/a> statement allows you to re-raise the exception:<\/p>\n<p>\u5982\u679c\u4f60\u9700\u8981\u77e5\u9053\u54ea\u4e2a\u5f02\u5e38\u88ab\u629b\u51fa\uff0c\u4f46\u4f60\u53c8\u4e0d\u60f3\u5904\u7406\u5b83\uff0c\u4e00\u4e2a\u7b80\u5355\u7684raise\u8bed\u53e5\u5141\u8bb8\u4f60\u91cd\u65b0\u629b\u51fa\u8be5\u5f02\u5e38\u3002<\/p>\n<div class=\"cnblogs_code\">\n<div class=\"cnblogs_code_toolbar\"><span class=\"cnblogs_code_copy\"><a title=\"\u590d\u5236\u4ee3\u7801\"><img decoding=\"async\" src=\"http:\/\/zerobox.org\/notes\/wp-content\/uploads\/2015\/03\/9148256b89e79e5d03bf03a93cf12ac4.gif\" alt=\"\u590d\u5236\u4ee3\u7801\" \/><\/a><\/span><\/div>\n<pre>&gt;&gt;&gt; try:\r\n...     raise NameError('HiThere')\r\n... except NameError:\r\n...     print('An exception flew by!')\r\n...     raise\r\n...\r\nAn exception flew by!\r\nTraceback (most recent call last):\r\n  File \"&lt;stdin&gt;\", line 2, in ?\r\nNameError: HiThere<\/pre>\n<div class=\"cnblogs_code_toolbar\"><span class=\"cnblogs_code_copy\"><a title=\"\u590d\u5236\u4ee3\u7801\"><img decoding=\"async\" src=\"http:\/\/zerobox.org\/notes\/wp-content\/uploads\/2015\/03\/9148256b89e79e5d03bf03a93cf12ac4.gif\" alt=\"\u590d\u5236\u4ee3\u7801\" \/><\/a><\/span><\/div>\n<\/div>\n<h2>8.5. User-defined Exceptions<\/h2>\n<p>Programs may name their own exceptions by creating a new exception class (see <a class=\"reference internal\" href=\"https:\/\/docs.python.org\/3.4\/tutorial\/classes.html#tut-classes\"><em>Classes<\/em><\/a> for more about Python classes). Exceptions should typically be derived from the <a class=\"reference internal\" title=\"Exception\" href=\"https:\/\/docs.python.org\/3.4\/library\/exceptions.html#Exception\"><tt class=\"xref py py-exc docutils literal\">Exception<\/tt><\/a> class, either directly or indirectly. For example:<\/p>\n<p>\u7a0b\u5e8f\u8005\u53ef\u80fd\u5e0c\u671b\u81ea\u5df1\u80fd\u521b\u5efa\u4e00\u4e2a\u65b0\u7684\u5f02\u5e38\u7c7b\u3002\u90a3\u4e48\u8fd9\u4e2a\u5f02\u5e38\u7c7b\u5fc5\u987b\u76f4\u63a5\u6216\u95f4\u63a5\u7684\u7ee7\u627fException\u7c7b\u3002\u4f8b\u5982\uff1a<\/p>\n<div class=\"cnblogs_code\">\n<div class=\"cnblogs_code_toolbar\"><span class=\"cnblogs_code_copy\"><a title=\"\u590d\u5236\u4ee3\u7801\"><img decoding=\"async\" src=\"http:\/\/zerobox.org\/notes\/wp-content\/uploads\/2015\/03\/9148256b89e79e5d03bf03a93cf12ac4.gif\" alt=\"\u590d\u5236\u4ee3\u7801\" \/><\/a><\/span><\/div>\n<pre>&gt;&gt;&gt; class MyError(Exception):\r\n...     def __init__(self, value):\r\n...         self.value = value\r\n...     def __str__(self):\r\n...         return repr(self.value)\r\n...\r\n&gt;&gt;&gt; try:\r\n...     raise MyError(2*2)\r\n... except MyError as e:\r\n...     print('My exception occurred, value:', e.value)\r\n...\r\nMy exception occurred, value: 4\r\n&gt;&gt;&gt; raise MyError('oops!')\r\nTraceback (most recent call last):\r\n  File \"&lt;stdin&gt;\", line 1, in ?\r\n__main__.MyError: 'oops!'<\/pre>\n<div class=\"cnblogs_code_toolbar\"><span class=\"cnblogs_code_copy\"><a title=\"\u590d\u5236\u4ee3\u7801\"><img decoding=\"async\" src=\"http:\/\/zerobox.org\/notes\/wp-content\/uploads\/2015\/03\/9148256b89e79e5d03bf03a93cf12ac4.gif\" alt=\"\u590d\u5236\u4ee3\u7801\" \/><\/a><\/span><\/div>\n<\/div>\n<p>In this example, the default <a class=\"reference internal\" title=\"object.__init__\" href=\"https:\/\/docs.python.org\/3.4\/reference\/datamodel.html#object.__init__\"><tt class=\"xref py py-meth docutils literal\">__init__()<\/tt><\/a> of <a class=\"reference internal\" title=\"Exception\" href=\"https:\/\/docs.python.org\/3.4\/library\/exceptions.html#Exception\"><tt class=\"xref py py-class docutils literal\">Exception<\/tt><\/a> has been overridden. The new behavior simply creates the <em>value<\/em> attribute. This replaces the default behavior of creating the <em>args<\/em> attribute.<\/p>\n<p>\u5728\u8fd9\u4e2a\u4f8b\u5b50\u4e2d\uff0cException\u7c7b\u9ed8\u8ba4\u7684__init__()\u51fd\u6570\u88ab\u8986\u76d6\u4e86\u3002\u65b0\u7684__init__()\u51fd\u6570\u4ec5\u4ec5\u521b\u5efa\u4e00\u4e2avalue\u5c5e\u6027\u3002\u8fd9\u4e2a\u66ff\u6362\u4e86args\u5c5e\u6027\u7684\u9ed8\u8ba4\u884c\u4e3a\u3002<\/p>\n<p>Exception classes can be defined which do anything any other class can do, but are usually kept simple, often only offering a number of attributes that allow information about the error to be extracted by handlers for the exception. When creating a module that can raise several distinct errors, a common practice is to create a base class for exceptions defined by that module, and subclass that to create specific exception classes for different error conditions:<\/p>\n<p>\u4e00\u4e2a\u5f02\u5e38\u7c7b\u53ef\u4ee5\u50cf\u5176\u4ed6\u7c7b\u4e00\u6837\u505a\u4efb\u4f55\u4e8b\u60c5\uff0c\u4f46\u662f\u901a\u5e38\u90fd\u662f\u4fdd\u6301\u7b80\u5355\u7684\u5f62\u5f0f\uff0c\u901a\u5e38\u662f\u4ec5\u4ec5\u63d0\u4f9b\u4e00\u4e9b\u5c5e\u6027\u6765\u5173\u8054\u9519\u8bef\u4fe1\u606f\uff0c\u5e76\u5f53\u5904\u7406\u7a0b\u5e8f\u5f15\u53d1\u5f02\u5e38\u65f6\u8c03\u7528\u3002\u5f53\u521b\u5efa\u4e00\u4e2a\u6a21\u5757\u53ef\u4ee5\u5f15\u53d1\u51e0\u79cd\u4e0d\u540c\u7684\u9519\u8bef\u65f6\uff0c\u4e00\u4e2a\u666e\u904d\u7684\u505a\u6cd5\u662f\u521b\u5efa\u4e00\u4e2a\u57fa\u7c7b\uff0c\u7136\u540e\u5b50\u7c7b\u5904\u7406\u4e0d\u540c\u7684\u5f02\u5e38\u9519\u8bef\u7c7b\u578b\u3002<\/p>\n<div class=\"cnblogs_code\">\n<div class=\"cnblogs_code_toolbar\"><span class=\"cnblogs_code_copy\"><a title=\"\u590d\u5236\u4ee3\u7801\"><img decoding=\"async\" src=\"http:\/\/zerobox.org\/notes\/wp-content\/uploads\/2015\/03\/9148256b89e79e5d03bf03a93cf12ac4.gif\" alt=\"\u590d\u5236\u4ee3\u7801\" \/><\/a><\/span><\/div>\n<pre>class Error(Exception):\r\n    \"\"\"Base class for exceptions in this module.\"\"\"\r\n    pass\r\n\r\nclass InputError(Error):\r\n    \"\"\"Exception raised for errors in the input.\r\n\r\n    Attributes:\r\n        expression -- input expression in which the error occurred\r\n        message -- explanation of the error\r\n    \"\"\"\r\n\r\n    def __init__(self, expression, message):\r\n        self.expression = expression\r\n        self.message = message\r\n\r\nclass TransitionError(Error):\r\n    \"\"\"Raised when an operation attempts a state transition that's not\r\n    allowed.\r\n\r\n    Attributes:\r\n        previous -- state at beginning of transition\r\n        next -- attempted new state\r\n        message -- explanation of why the specific transition is not allowed\r\n    \"\"\"\r\n\r\n    def __init__(self, previous, next, message):\r\n        self.previous = previous\r\n        self.next = next\r\n        self.message = message<\/pre>\n<div class=\"cnblogs_code_toolbar\"><span class=\"cnblogs_code_copy\"><a title=\"\u590d\u5236\u4ee3\u7801\"><img decoding=\"async\" src=\"http:\/\/zerobox.org\/notes\/wp-content\/uploads\/2015\/03\/9148256b89e79e5d03bf03a93cf12ac4.gif\" alt=\"\u590d\u5236\u4ee3\u7801\" \/><\/a><\/span><\/div>\n<\/div>\n<p>Most exceptions are defined with names that end in \u201cError,\u201d similar to the naming of the standard exceptions.<\/p>\n<p>\u5927\u591a\u6570\u81ea\u5b9a\u4e49\u7684\u5f02\u5e38\u7c7b\u7684\u540d\u5b57\u90fd\u662f\u4ee5&#8221;Error&#8221;\u7ed3\u5c3e\uff0c\u8fd9\u7c7b\u4f3c\u4e8e\u6807\u51c6\u5f02\u5e38\u7c7b\u7684\u98ce\u683c\u3002<\/p>\n<p>Many standard modules define their own exceptions to report errors that may occur in functions they define. More information on classes is presented in chapter <a class=\"reference internal\" href=\"https:\/\/docs.python.org\/3.4\/tutorial\/classes.html#tut-classes\"><em>Classes<\/em><\/a>.<\/p>\n<p>\u8bb8\u591a\u6807\u51c6\u7684\u6a21\u5757\u90fd\u5b9a\u4e49\u4e86\u4ed6\u4eec\u81ea\u5df1\u7684\u5f02\u5e38\u6765\u62a5\u544a\u9519\u8bef\u3002\u5173\u4e8e\u7c7b\u7684\u63cf\u8ff0\uff0c\u8bf7\u67e5\u9605Classes\u7ae0\u8282\u3002<\/p>\n<h2>8.6. Defining Clean-up Actions<\/h2>\n<p>The <a class=\"reference internal\" href=\"https:\/\/docs.python.org\/3.4\/reference\/compound_stmts.html#try\"><tt class=\"xref std std-keyword docutils literal\">try<\/tt><\/a> statement has another optional clause which is intended to define clean-up actions that must be executed under all circumstances. For example:<\/p>\n<p>try\u8bed\u53e5\u8fd8\u6709\u53e6\u4e00\u4e2a\u53ef\u9009\u7684\u5b50\u5757\uff0c\u8fd9\u4e2a\u5b50\u5757\u4e3b\u8981\u662f\u7528\u6765\u505a\u4e00\u4e9b\u6e05\u7406\u5de5\u4f5c\u3002<\/p>\n<div class=\"cnblogs_code\">\n<div class=\"cnblogs_code_toolbar\"><span class=\"cnblogs_code_copy\"><a title=\"\u590d\u5236\u4ee3\u7801\"><img decoding=\"async\" src=\"http:\/\/zerobox.org\/notes\/wp-content\/uploads\/2015\/03\/9148256b89e79e5d03bf03a93cf12ac4.gif\" alt=\"\u590d\u5236\u4ee3\u7801\" \/><\/a><\/span><\/div>\n<pre>&gt;&gt;&gt; try:\r\n...     raise KeyboardInterrupt\r\n... finally:\r\n...     print('Goodbye, world!')\r\n...\r\nGoodbye, world!\r\nKeyboardInterrupt<\/pre>\n<div class=\"cnblogs_code_toolbar\"><span class=\"cnblogs_code_copy\"><a title=\"\u590d\u5236\u4ee3\u7801\"><img decoding=\"async\" src=\"http:\/\/zerobox.org\/notes\/wp-content\/uploads\/2015\/03\/9148256b89e79e5d03bf03a93cf12ac4.gif\" alt=\"\u590d\u5236\u4ee3\u7801\" \/><\/a><\/span><\/div>\n<\/div>\n<p>A <em>finally clause<\/em> is always executed before leaving the <a class=\"reference internal\" href=\"https:\/\/docs.python.org\/3.4\/reference\/compound_stmts.html#try\"><tt class=\"xref std std-keyword docutils literal\">try<\/tt><\/a> statement, whether an exception has occurred or not. When an exception has occurred in the <a class=\"reference internal\" href=\"https:\/\/docs.python.org\/3.4\/reference\/compound_stmts.html#try\"><tt class=\"xref std std-keyword docutils literal\">try<\/tt><\/a> clause and has not been handled by an <a class=\"reference internal\" href=\"https:\/\/docs.python.org\/3.4\/reference\/compound_stmts.html#except\"><tt class=\"xref std std-keyword docutils literal\">except<\/tt><\/a> clause (or it has occurred in a<a class=\"reference internal\" href=\"https:\/\/docs.python.org\/3.4\/reference\/compound_stmts.html#except\"><tt class=\"xref std std-keyword docutils literal\">except<\/tt><\/a> or <a class=\"reference internal\" href=\"https:\/\/docs.python.org\/3.4\/reference\/compound_stmts.html#else\"><tt class=\"xref std std-keyword docutils literal\">else<\/tt><\/a> clause), it is re-raised after the <a class=\"reference internal\" href=\"https:\/\/docs.python.org\/3.4\/reference\/compound_stmts.html#finally\"><tt class=\"xref std std-keyword docutils literal\">finally<\/tt><\/a> clause has been executed. The <a class=\"reference internal\" href=\"https:\/\/docs.python.org\/3.4\/reference\/compound_stmts.html#finally\"><tt class=\"xref std std-keyword docutils literal\">finally<\/tt><\/a> clause is also executed \u201con the way out\u201d when any other clause of the <a class=\"reference internal\" href=\"https:\/\/docs.python.org\/3.4\/reference\/compound_stmts.html#try\"><tt class=\"xref std std-keyword docutils literal\">try<\/tt><\/a> statement is left via a <a class=\"reference internal\" href=\"https:\/\/docs.python.org\/3.4\/reference\/simple_stmts.html#break\"><tt class=\"xref std std-keyword docutils literal\">break<\/tt><\/a>, <a class=\"reference internal\" href=\"https:\/\/docs.python.org\/3.4\/reference\/simple_stmts.html#continue\"><tt class=\"xref std std-keyword docutils literal\">continue<\/tt><\/a> or <a class=\"reference internal\" href=\"https:\/\/docs.python.org\/3.4\/reference\/simple_stmts.html#return\"><tt class=\"xref std std-keyword docutils literal\">return<\/tt><\/a> statement. A more complicated example:<\/p>\n<p>\u5728\u4f8b\u5b50try\u8bed\u53e5\u4e4b\u524d\uff0cfinally\u5b50\u5757\u603b\u662f\u5fc5\u987b\u6267\u884c\uff0c\u4e0d\u7ba1\u662f\u5426\u53d1\u751f\u5f02\u5e38\u3002\u5f53\u4e00\u4e2a\u5f02\u5e38\u5728try\u8bed\u53e5\u5757\u4e2d\u5f15\u53d1\u800c\u6ca1\u6709except\u5b50\u5757\u5904\u7406\uff0c\u5b83\u4f1a\u5728finally\u5b50\u5757\u6267\u884c\u5b8c\u540e\u5f15\u53d1\u5f02\u5e38\u3002\u4e0d\u7ba1\u5728try\u8bed\u53e5\u5757\u4e2d\u65f6\u7531\u4e8ebreak,continue\u6216\u8005return\u8bed\u53e5\u4e2d\u65ad\u4e86\uff0cfinally\u8bed\u53e5\u8fd8\u662f\u8981\u6267\u884c\u3002\u4f8b\u5982\uff1a<\/p>\n<div class=\"cnblogs_code\">\n<div class=\"cnblogs_code_toolbar\"><span class=\"cnblogs_code_copy\"><a title=\"\u590d\u5236\u4ee3\u7801\"><img decoding=\"async\" src=\"http:\/\/zerobox.org\/notes\/wp-content\/uploads\/2015\/03\/9148256b89e79e5d03bf03a93cf12ac4.gif\" alt=\"\u590d\u5236\u4ee3\u7801\" \/><\/a><\/span><\/div>\n<pre>&gt;&gt;&gt; def divide(x, y):\r\n...     try:\r\n...         result = x \/ y\r\n...     except ZeroDivisionError:\r\n...         print(\"division by zero!\")\r\n...     else:\r\n...         print(\"result is\", result)\r\n...     finally:\r\n...         print(\"executing finally clause\")\r\n...\r\n&gt;&gt;&gt; divide(2, 1)\r\nresult is 2.0\r\nexecuting finally clause\r\n&gt;&gt;&gt; divide(2, 0)\r\ndivision by zero!\r\nexecuting finally clause\r\n&gt;&gt;&gt; divide(\"2\", \"1\")\r\nexecuting finally clause\r\nTraceback (most recent call last):\r\n  File \"&lt;stdin&gt;\", line 1, in ?\r\n  File \"&lt;stdin&gt;\", line 3, in divide\r\nTypeError: unsupported operand type(s) for \/: 'str' and 'str'<\/pre>\n<div class=\"cnblogs_code_toolbar\"><span class=\"cnblogs_code_copy\"><a title=\"\u590d\u5236\u4ee3\u7801\"><img decoding=\"async\" src=\"http:\/\/zerobox.org\/notes\/wp-content\/uploads\/2015\/03\/9148256b89e79e5d03bf03a93cf12ac4.gif\" alt=\"\u590d\u5236\u4ee3\u7801\" \/><\/a><\/span><\/div>\n<\/div>\n<p>As you can see, the <a class=\"reference internal\" href=\"https:\/\/docs.python.org\/3.4\/reference\/compound_stmts.html#finally\"><tt class=\"xref std std-keyword docutils literal\">finally<\/tt><\/a> clause is executed in any event. The <a class=\"reference internal\" title=\"TypeError\" href=\"https:\/\/docs.python.org\/3.4\/library\/exceptions.html#TypeError\"><tt class=\"xref py py-exc docutils literal\">TypeError<\/tt><\/a> raised by dividing two strings is not handled by the <a class=\"reference internal\" href=\"https:\/\/docs.python.org\/3.4\/reference\/compound_stmts.html#except\"><tt class=\"xref std std-keyword docutils literal\">except<\/tt><\/a> clause and therefore re-raised after the <a class=\"reference internal\" href=\"https:\/\/docs.python.org\/3.4\/reference\/compound_stmts.html#finally\"><tt class=\"xref std std-keyword docutils literal\">finally<\/tt><\/a> clause has been executed.<\/p>\n<p>\u6b63\u5982\u4f60\u6240\u770b\u89c1\u7684\uff0cfinally\u5b50\u5757\u603b\u662f\u4f1a\u6267\u884c\u3002\u4e24\u4e2a\u5b57\u7b26\u4e32\u76f8\u9664\u5f15\u53d1\u7684TypeError\u5f02\u5e38\u6ca1\u6709\u88abexcept\u5b50\u5757\u5904\u7406\uff0c\u56e0\u6b64\uff0c\u5728finally\u5b50\u5757\u6267\u884c\u5b8c\u540e\u91cd\u65b0\u629b\u51fa\u3002<\/p>\n<p>In real world applications, the <a class=\"reference internal\" href=\"https:\/\/docs.python.org\/3.4\/reference\/compound_stmts.html#finally\"><tt class=\"xref std std-keyword docutils literal\">finally<\/tt><\/a> clause is useful for releasing external resources (such as files or network connections), regardless of whether the use of the resource was successful.<\/p>\n<p>\u5728\u771f\u5b9e\u7684\u7a0b\u5e8f\u4e16\u754c\u4e2d\uff0cfianlly\u5b50\u5757\u901a\u5e38\u662f\u7528\u6765\u91ca\u653e\u4e00\u4e0b\u989d\u5916\u7684\u8d44\u6e90\uff0c\u4e0d\u7ba1\u8d44\u6e90\u662f\u5426\u88ab\u4f7f\u7528\u6210\u529f\u3002<\/p>\n<h2>8.7. Predefined Clean-up Actions<\/h2>\n<p>Some objects define standard clean-up actions to be undertaken when the object is no longer needed, regardless of whether or not the operation using the object succeeded or failed. Look at the following example, which tries to open a file and print its contents to the screen.<\/p>\n<p>\u6709\u4e9b\u5bf9\u8c61\u5b9a\u4e49\u4e86\u6807\u51c6\u7684\u6e05\u7406\u64cd\u4f5c\u3002\u5f53\u5bf9\u8c61\u4e0d\u518d\u9700\u8981\u4f7f\u7528\u7684\u65f6\u5019\uff0c\u5c31\u4f1a\u81ea\u52a8\u6e05\u7406\u8d44\u6e90\uff0c\u4e0d\u7ba1\u5bf9\u8c61\u8c03\u7528\u7684\u64cd\u4f5c\u662f\u5426\u6210\u529f\u3002\u770b\u4e0b\u9762\u7684\u4f8b\u5b50\uff0c\u5c1d\u8bd5\u6253\u5f00\u4e00\u4e2a\u6587\u4ef6\uff0c\u5e76\u5c06\u5185\u5bb9\u8f93\u51fa\u5230\u5c4f\u5e55\u4e0a\u3002<\/p>\n<div class=\"cnblogs_code\">\n<pre>for line in open(\"myfile.txt\"):\r\n    print(line, end=\"\")<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>The problem with this code is that it leaves the file open for an indeterminate amount of time after this part of the code has finished executing. This is not an issue in simple scripts, but can be a problem for larger applications. The<a class=\"reference internal\" href=\"https:\/\/docs.python.org\/3.4\/reference\/compound_stmts.html#with\"><tt class=\"xref std std-keyword docutils literal\">with<\/tt><\/a> statement allows objects like files to be used in a way that ensures they are always cleaned up promptly and correctly.<\/p>\n<p>\u8fd9\u6bb5\u4ee3\u7801\u7684\u95ee\u9898\u662f\uff1a\u5f53\u8fd9\u90e8\u5206\u7684\u4ee3\u7801\u6267\u884c\u5b8c\u6bd5\u540e\uff0c\u6587\u4ef6\u4e00\u76f4\u5904\u4e8e\u6253\u5f00\u7684\u72b6\u6001\u3002\u8fd9\u5728\u4e00\u4e2a\u7b80\u5355\u7684\u811a\u672c\u4e2d\u4e0d\u4f1a\u6709\u4ec0\u4e48\u95ee\u9898\uff0c\u4f46\u662f\u5728\u4e00\u4e2a\u5927\u7684\u7a0b\u5e8f\u4e2d\u53ef\u80fd\u4f1a\u51fa\u73b0\u95ee\u9898\u3002with\u8bed\u53e5\u5141\u8bb8\u7c7b\u4f3c\u4e8e\u6587\u4ef6\u5bf9\u8c61\u7684\u5bf9\u8c61\u5728\u4f7f\u7528\u540e\uff0c\u786e\u4fdd\u4ed6\u4eec\u603b\u662f\u5408\u9002\u7684\u3001\u6b63\u786e\u7684\u88ab\u6e05\u7406\u6389\u3002<\/p>\n<div class=\"cnblogs_code\">\n<pre>with open(\"myfile.txt\") as f:\r\n    for line in f:\r\n        print(line, end=\"\")<\/pre>\n<\/div>\n<p>After the statement is executed, the file <em>f<\/em> is always closed, even if a problem was encountered while processing the lines. Objects which, like files, provide predefined clean-up actions will indicate this in their documentation.<\/p>\n<p>\u5f53\u8bed\u53e5\u6267\u884c\u540e\uff0cf\u5bf9\u8c61\u603b\u662f\u4f1a\u5173\u95ed\uff0c\u65e2\u4f7f\u5728\u5904\u7406\u6587\u4ef6\u7684\u8fc7\u7a0b\u4e2d\u51fa\u73b0\u4e86\u95ee\u9898\u3002\u7c7b\u4f3c\u4e8e\u6587\u4ef6\u7684\u5bf9\u8c61\u4ed6\u4eec\u63d0\u4f9b\u4e86\u63d0\u524d\u6e05\u7406\u8d44\u6e90\u7684\u64cd\u4f5c\uff0c\u8fd9\u4e9b\u5185\u5bb9\u53ef\u4ee5\u53c2\u9605\u8fd9\u4e9b\u5bf9\u8c61\u76f8\u5173\u7684\u6587\u6863\u3002<\/p>\n","protected":false},"excerpt":{"rendered":"<p>8.1. Syntax Errors Syntax errors, also k &hellip;<\/p>\n<p class=\"read-more\"><a href=\"http:\/\/zerobox.org\/notes\/988.html\">\u7ee7\u7eed\u9605\u8bfb &raquo;<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[],"tags":[48],"class_list":["post-988","post","type-post","status-publish","format-standard","hentry","tag-python"],"views":2111,"_links":{"self":[{"href":"http:\/\/zerobox.org\/notes\/wp-json\/wp\/v2\/posts\/988","targetHints":{"allow":["GET"]}}],"collection":[{"href":"http:\/\/zerobox.org\/notes\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/zerobox.org\/notes\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/zerobox.org\/notes\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/zerobox.org\/notes\/wp-json\/wp\/v2\/comments?post=988"}],"version-history":[{"count":0,"href":"http:\/\/zerobox.org\/notes\/wp-json\/wp\/v2\/posts\/988\/revisions"}],"wp:attachment":[{"href":"http:\/\/zerobox.org\/notes\/wp-json\/wp\/v2\/media?parent=988"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/zerobox.org\/notes\/wp-json\/wp\/v2\/categories?post=988"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/zerobox.org\/notes\/wp-json\/wp\/v2\/tags?post=988"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}