我怎样才能编写一个捕获所有异常的try/except块?
try
except
你可以,但你可能不应该:
try: do_something() except: print("Caught it!")
但是,这也会捕获异常KeyboardInterrupt,您通常不希望这样,对吗?除非您立即重新引发异常 - 请参阅文档中的以下示例:
KeyboardInterrupt
try: f = open('myfile.txt') s = f.readline() i = int(s.strip()) except IOError as (errno, strerror): print("I/O error({0}): {1}".format(errno, strerror)) except ValueError: print("Could not convert data to an integer.") except: print("Unexpected error:", sys.exc_info()[0]) raise