8.3. Handling Exceptions 59 (continued from previous page) (continues on next page) Python Tutorial, Release 3.9.5 Note that if the except clauses were reversed (with except B first), it would have printed B, B, B — the first matching except clause is triggered. 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): The$_{try}$ …$_{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: 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’t raised by the code being protected by the$_{try}$ …$_{except}$statement. When an exception occurs, it may have an associated value, also known as the exception’s argument . The presence and type of the argument depend on the exception type. The except clause may specify a variable after the exception name. 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}$ . One may also instantiate an exception first before raising it and add any attributes to it as desired. >>> try : ... raise Exception('spam','eggs') ... except Exception as inst: ... print(type(inst)) # the exception instance ... print(inst.args) # arguments stored in .args ... print(inst) # __str__ allows args to be printed directly, ... # but may be overridden in exception subclasses ... x, y=inst.args # unpack args ... print('x =', x) ... print('y =', y) for arg in sys.argv[1:]: try : f =open(arg,'r') except OSError: print('cannot open', arg) else : print(arg,'has',len(f.readlines()), 'lines') f.close() import sys try : f =open('myfile.txt ') s =f.readline() i =int(s.strip()) except OSError as err: print("OS error: {0} ".format(err)) except ValueError: print("Could not convert data to an integer. ") except : print("Unexpected error:", sys.exc_info()[ 0]) raise except D: print("D") except C: print("C") except B: print("B")