यह एक सामान्य नियम है कि हालांकि आप नीचे दिए गए जैसे कोड का उपयोग करके सभी एक्सेप्शन पकड़ सकते हैं, आपको ऐसा नहीं करना चाहिए:
try:
# do_something()
except:
print("Exception Caught!")
हालांकि, यह KeyboardInterrupt जैसे एक्सेप्शन भी पकड़ लेगा जिनमें हम रुचि नहीं रखते। जब तक आप एक्सेप्शन को तुरंत फिर से नहीं उठाते - हम एक्सेप्शन को पकड़ नहीं पाएंगे:
try:
f = open('file.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
हमें निम्न जैसा आउटपुट मिलता है, यदि file.txt स्क्रिप्ट के समान फोल्डर में उपलब्ध नहीं है।
I/O error(2): No such file or directory