{"id":1594,"date":"2014-11-15T03:37:08","date_gmt":"2014-11-15T03:37:08","guid":{"rendered":"http:\/\/ixyzero.com\/blog\/?p=1594"},"modified":"2014-11-15T03:37:08","modified_gmt":"2014-11-15T03:37:08","slug":"python%e7%9a%84%e5%bc%82%e5%b8%b8%e5%a4%84%e7%90%86","status":"publish","type":"post","link":"https:\/\/ixyzero.com\/blog\/archives\/1594.html","title":{"rendered":"Python\u7684\u5f02\u5e38\u5904\u7406"},"content":{"rendered":"<p>\u4e4b\u524d\u6ca1\u600e\u4e48\u7528\u201c\u5f02\u5e38\u5904\u7406\u4ee3\u7801\u5757\u201d\u7684\u4e60\u60ef\uff0c\u4e00\u6765\u662f\u56e0\u4e3a\u4ee3\u7801\u91cf\u8f83\u5c0f\u3001\u5de5\u7a0b\u4e5f\u4e0d\u5927\uff0c\u57fa\u672c\u4e0a\u5404\u79cd\u95ee\u9898\u90fd\u5904\u4e8e\u53ef\u63a7\u7684\u72b6\u6001\u4e0b\uff08\u6211\u4e00\u822c\u90fd\u662f\u5728\u5b8c\u5168\u8c03\u8bd5\u597d\u4e86\u4e4b\u540e\u624d\u5f00\u59cb\u771f\u6b63\u5c06\u4ee3\u7801\u653e\u5165crontab\u4e2d\u5b9a\u671f\u6267\u884c\u7684\uff0c\u6ca1\u4e8b\u7684\u65f6\u5019\u4e5f\u4f1a\u770b\u770b\u6267\u884c\u7684\u7ed3\u679c\u662f\u5426\u7b26\u5408\u9884\u671f\uff0c\u6240\u4ee5\u8fd9\u6837\u505a\u4e86\u5f88\u4e45\u4e5f\u6ca1\u4ec0\u4e48\u5927\u7684\u95ee\u9898\u51fa\u73b0\uff09\uff1b\u4e8c\u6765\u662f\u6ca1\u8fd9\u4e2a\u4e60\u60ef\uff08\u6ca1\u5403\u8fc7\u8fd9\u65b9\u9762\u7684\u4e8f\u2026\u2026\uff09\uff0c\u89c9\u5f97\u6dfb\u52a0\u4e86\u8fd9\u4e9b\u201c\u65e0\u7528\u201d\u7684\u4ee3\u7801\u4e4b\u540e\uff0c\u663e\u5f97\u6709\u4e9b\u5197\u4f59\uff0c\u4e0d\u7b26\u5408Python\u7b80\u6d01\u7684\u98ce\u683c\u3002<\/p>\n<p>\u4f46\u662f\u6709\u65f6\u5019\u5728\u628a\u4ee3\u7801\u4ea4\u7ed9\u522b\u4eba\u7684\u65f6\u5019\uff0c\u56e0\u4e3a\u524d\u671f\u4f60\u6ca1\u529e\u6cd5\u6e05\u695a\u7684\u77e5\u9053\u4ee3\u7801\u8981\u5728\u4e00\u4e2a\u4ec0\u4e48\u6837\u7684\u73af\u5883\u4e0b\u6267\u884c\uff0c\u4e5f\u5c31\u6ca1\u529e\u6cd5\u8fdb\u884c\u5168\u9762\u7684\u5206\u6790\u3001\u8c03\u8bd5\uff0c\u6240\u4ee5\uff0c\u8fd9\u65f6\u5019\u4e4b\u524d\u7684\u4ee3\u7801\u4e60\u60ef\u5c31\u6709\u95ee\u9898\u4e86\u2014\u2014\u51fa\u4e86\u95ee\u9898\u6ca1\u6cd5\u5904\u7406\uff0c\u4e8e\u662f\uff0c\u5f00\u59cb\u5728\u4ee3\u7801\u4e2d\u52a0\u5165\u4e86\u5f02\u5e38\u5904\u7406\uff0c\u4e0b\u9762\u662f\u5728\u5b66\u4e60\u8fc7\u7a0b\u4e2d\u8bb0\u5f55\u7684\u4e00\u4e9b\u5185\u5bb9\uff0c\u65b9\u4fbf\u968f\u65f6\u56de\u987e\uff1a<\/p>\n<ul>\n<li><strong>\u5b98\u65b9\u6587\u6863<\/strong> <a href=\"https:\/\/docs.python.org\/2\/tutorial\/errors.html\" target=\"_blank\">https:\/\/docs.python.org\/2\/tutorial\/errors.html<\/a><\/li>\n<li><strong>Stackoverflow<\/strong>\u4e0a\u7684\u4e00\u4e9b\u95ee\u7b54\uff1a\n<ul>\n<li style=\"padding-left: 30px;\"><a href=\"http:\/\/stackoverflow.com\/questions\/730764\/try-except-in-python-how-to-properly-ignore-exceptions\" target=\"_blank\">http:\/\/stackoverflow.com\/questions\/730764\/try-except-in-python-how-to-properly-ignore-exceptions<\/a><\/li>\n<li style=\"padding-left: 30px;\"><a href=\"http:\/\/stackoverflow.com\/questions\/1319615\/proper-way-to-declare-custom-exceptions-in-modern-python\" target=\"_blank\">http:\/\/stackoverflow.com\/questions\/1319615\/proper-way-to-declare-custom-exceptions-in-modern-python<\/a><\/li>\n<li style=\"padding-left: 30px;\"><a href=\"http:\/\/stackoverflow.com\/questions\/9823936\/python-how-do-i-know-what-type-of-exception-occured\" target=\"_blank\">http:\/\/stackoverflow.com\/questions\/9823936\/python-how-do-i-know-what-type-of-exception-occured<\/a><\/li>\n<\/ul>\n<\/li>\n<li><a href=\"http:\/\/en.wikibooks.org\/wiki\/Python_Programming\/Exceptions\" target=\"_blank\">Python_Programming_Exceptions__wikibooks<\/a><\/li>\n<li><a href=\"http:\/\/www.dotnetperls.com\/try-python\" target=\"_blank\">Python Try and Except: Exception Handling Examples<\/a><\/li>\n<li><a href=\"http:\/\/search.aol.com\/aol\/search?q=python+try\" target=\"_blank\">AOL\u641c\u7d22\u7ed3\u679c<\/a><\/li>\n<\/ul>\n<hr \/>\n<pre class=\"lang:default decode:true \">try:\n    doSomething()\nexcept:\n    pass\n###or###\ntry:\n    doSomething()\nexcept Exception:\n    pass<\/pre>\n<p><span style=\"color: #ff0000;\">The difference is, that the first one will also catch KeyboardInterrupt, SystemExit and stuff like that, which are derived directly from <strong>exceptions.BaseException<\/strong>, not <strong>exceptions.Exception<\/strong>.(<span style=\"color: #000000;\">\u4e0a\u9762\u76842\u4e2atry-catch\u8bed\u53e5\u5757\u7684\u533a\u522b\u4e4b\u5904\u5728\u4e8e\uff0c\u7b2c1\u4e2atry-catch\u4f1a\u6355\u6349\u7c7b\u4f3c\u4e8eKeyboardInternet\u3001SystemExit\u8fd9\u6837\u7684\u5f02\u5e38\u2014\u2014\u57fa\u672c\u4e0a\u6240\u6709\u7684\u5f02\u5e38\u90fd\u5305\u62ec\u8fdb\u53bb\u4e86\uff0c\u8fd9\u662f\u56e0\u4e3aexcept\u540e\u9762\u6ca1\u6709\u4efb\u4f55\u8bf4\u660e\uff0c\u56e0\u6b64\u76f4\u63a5\u7ee7\u627f\u7684\u662fexceptions.BaseException\u800c\u4e0d\u662fexceptions.Exception<\/span>)<\/span><\/p>\n<p>See documentation for details:<br \/>\n\u2022 try statement \u2014 <a href=\"http:\/\/docs.python.org\/reference\/compound_stmts.html#try\" target=\"_blank\">http:\/\/docs.python.org\/reference\/compound_stmts.html#try<\/a><br \/>\n\u2022 exceptions \u2014 <a href=\"http:\/\/docs.python.org\/library\/exceptions\" target=\"_blank\">http:\/\/docs.python.org\/library\/exceptions<\/a><\/p>\n<hr \/>\n<h5><a href=\"https:\/\/docs.python.org\/2\/tutorial\/errors.html#handling-exceptions\" target=\"_blank\">Handling Exceptions<\/a>\uff08\u5904\u7406\u5f02\u5e38\uff09<\/h5>\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 Control-C or whatever the operating system supports); note that a user-generated interruption is signalled by raising theKeyboardInterrupt exception.<\/p>\n<pre class=\"lang:default decode:true \">&gt;&gt;&gt; while True:\n...     try:\n...         x = int(raw_input(\"Please enter a number: \"))\n...         break\n...     except ValueError:\n...         print \"Oops!  That was no valid number.  Try again...\"\n...<\/pre>\n<p>The try statement works as follows\uff08try\u8bed\u53e5\u5757\u7684\u6267\u884c\u6d41\u7a0b\u5982\u4e0b\uff09:<\/p>\n<p>\u2022 First, the try clause (the statement(s) between the try and except keywords) is executed.\uff08\u9996\u5148\u6267\u884ctry\u540e\u9762\u7684\uff09<br \/>\n\u2022 If no exception occurs, the except clause is skipped and execution of the try statement is finished.\uff08\u5982\u679c\u6ca1\u6709\u5f02\u5e38\u53d1\u751f\uff0c\u5219except\u91cc\u9762\u7684\u8bed\u53e5\u5c31\u4e0d\u6267\u884c\u4e86\uff0ctry\u8bed\u53e5\u5757\u4e5f\u5c31\u6267\u884c\u7ed3\u675f\u4e86\uff09<br \/>\n\u2022 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 except keyword, the except clause is executed, and then execution continues after the try statement.\uff08\u5982\u679c\u5728try\u4e2d\u53d1\u751f\u4e86\u5f02\u5e38\uff0c\u5219try\u91cc\u9762\u5269\u4e0b\u7684\u90e8\u5206\u5c31\u4f1a\u88ab\u8df3\u8fc7\u4e0d\u6267\u884c\uff0c\u5982\u679cexcept\u540e\u9762\u7684\u5f02\u5e38\u7c7b\u578b\u548ctry\u91cc\u9762\u5f15\u53d1\u7684\u5f02\u5e38\u7c7b\u578b\u76f8\u540c\uff0c\u5219\u4f1a\u6267\u884cexcept\u91cc\u9762\u7684\u8bed\u53e5\uff0c\u5426\u5219\u5c31\u4f1a\u5728try\u8bed\u53e5\u5757\u6267\u884c\u4e4b\u540e\u629b\u51fa\u5f02\u5e38\uff09<br \/>\n\u2022 If an exception occurs which does not match the exception named in the except clause, it is passed on to outertry statements; if no handler is found, it is an unhandled exception and execution stops with a message as shown above.\uff08\u5982\u679c\u53d1\u751f\u7684\u5f02\u5e38\u548cexcept\u540e\u9762\u6307\u5b9a\u7684\u5f02\u5e38\u7c7b\u578b\u4e0d\u4e00\u81f4\uff0c\u5219\u5f02\u5e38\u5c31\u4f1a\u88ab\u629b\u5230try\u8bed\u53e5\u5757\u4e4b\u5916\uff0c\u7136\u540e\u5c31\u4f1a\u6709\u4e0a\u9762\u90a3\u6837\u7684\u9519\u8bef\u3002\uff09<\/p>\n<hr \/>\n<p>A try 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 try statement. <strong><span style=\"color: #ff0000;\">An except clause may name multiple exceptions as a parenthesized tuple\uff08\u4e00\u4e2aexcept\u8bed\u53e5\u53ef\u4ee5\u901a\u8fc7tuple\u6765\u6307\u5b9a\u591a\u4e2a\u5f02\u5e38\u7c7b\u578b\uff09<\/span><\/strong>, for example:<\/p>\n<pre class=\"lang:default decode:true \">... except (RuntimeError, TypeError, NameError):\n...     pass<\/pre>\n<p>Note that the parentheses around this tuple are required, because except ValueError, e: was the syntax used for what is normally written as except ValueError as e: in modern Python (described below). The old syntax is still supported for backwards compatibility. This means except RuntimeError, TypeError is not equivalent to except (RuntimeError, TypeError): but toexcept RuntimeError as TypeError: which is not what you want.<\/p>\n<p><strong><span style=\"color: #0000ff;\">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!<\/span><\/strong> 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<pre class=\"lang:default decode:true \">import sys\ntry:\n    f = open('myfile.txt')\n    s = f.readline()\n    i = int(s.strip())\nexcept IOError as e:\n    print \"I\/O error({0}): {1}\".format(e.errno, e.strerror)\nexcept ValueError:\n    print \"Could not convert data to an integer.\"\nexcept:\n    print \"Unexpected error:\", sys.exc_info()[0]\n    raise<\/pre>\n<p>The try &#8230; except statement has an optional else clause, 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<pre class=\"lang:default decode:true \">for arg in sys.argv[1:]:\n    try:\n        f = open(arg, 'r')\n    except IOError:\n        print 'cannot open', arg\n    else:\n        print arg, 'has', len(f.readlines()), 'lines'\n        f.close()<\/pre>\n<p>The use of the else clause is better than adding additional code to the try clause because it avoids accidentally catching an exception that wasn\u2019t raised by the code being protected by the try &#8230; except statement.<br \/>\nWhen an exception occurs, it may have an associated value, also known as the exception\u2019s argument. The presence and type of the argument depend on the exception type.<br \/>\nThe except clause may specify a variable after the exception name (or tuple). The variable is bound to an exception instance with the arguments stored in instance.args. For convenience, the exception instance defines __str__() so the arguments can be printed directly without having to reference .args.<br \/>\nOne may also instantiate an exception first before raising it and add any attributes to it as desired.<\/p>\n<pre class=\"lang:default decode:true \">&gt;&gt;&gt; try:\n...    raise Exception('spam', 'eggs')\n... except Exception as inst:\n...    print type(inst)     # the exception instance\n...    print inst.args      # arguments stored in .args\n...    print inst           # __str__ allows args to be printed directly\n...    x, y = inst.args\n...    print 'x =', x\n...    print 'y =', y\n...\n&lt;type 'exceptions.Exception'&gt;\n('spam', 'eggs')\n('spam', 'eggs')\nx = spam\ny = eggs<\/pre>\n<p>If an exception has an argument, it is printed as the last part (\u2018detail\u2019) of the message for unhandled exceptions.<br \/>\nException 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<pre class=\"lang:default decode:true \">&gt;&gt;&gt; def this_fails():\n...     x = 1\/0\n...\n&gt;&gt;&gt; try:\n...     this_fails()\n... except ZeroDivisionError as detail:\n...     print 'Handling run-time error:', detail\n...\nHandling run-time error: integer division or modulo by zero<\/pre>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>\u4e4b\u524d\u6ca1\u600e\u4e48\u7528\u201c\u5f02\u5e38\u5904\u7406\u4ee3\u7801\u5757\u201d\u7684\u4e60\u60ef\uff0c\u4e00\u6765\u662f\u56e0\u4e3a\u4ee3\u7801\u91cf\u8f83\u5c0f\u3001\u5de5\u7a0b\u4e5f\u4e0d\u5927\uff0c\u57fa\u672c\u4e0a\u5404\u79cd\u95ee\u9898\u90fd\u5904\u4e8e\u53ef\u63a7\u7684\u72b6\u6001\u4e0b\uff08\u6211\u4e00 [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[23,7],"tags":[8,394],"class_list":["post-1594","post","type-post","status-publish","format-standard","hentry","category-knowledgebase-2","category-programing","tag-python","tag-try-catch"],"views":3834,"_links":{"self":[{"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/posts\/1594","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/comments?post=1594"}],"version-history":[{"count":0,"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/posts\/1594\/revisions"}],"wp:attachment":[{"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/media?parent=1594"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/categories?post=1594"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/tags?post=1594"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}