https://docs.python.org/3/reference/compound_stmts.html#try
https://docs.python.org/3/library/exceptions.html#ExceptionGroup
The 'try' statement can be used used to specify exception handlers and/or cleanup code for a group of statements.
The 'except' clause(s) specify one or more exception handlers.
The 'finally' clause can be used to specify cleanup code which does not handle the exception, but is executed whether an exception occurred or not in the preceding code.
# Syntax.
# (1) try + except (one or more) + else (optional) + finally (optional)
# (2) try + finally
try:
statements
except ExceptionClass1: # matching ExceptionClass1
statements
except (ExceptionClass2, ExceptionClass3): # matching two exception classes
statements
except ExceptionClass4 as exception1: # exception1 is an instance
statements
except (ExceptionClass4, ExceptionClass5) as exception2:
statements
#except: # if present, must be the last; it matches any exception
except Exception: # recommended
statements
else: # optional, executed if no exception was raised
statements
finally: # if present, it is always executed
statements
L = []
# L = [1, 2, 3]
try:
print(L[1])
except IndexError:
print("exception is present")
else:
print("no exception")
print("after try")
afile = open("book.txt")
try: # working with the file
text = afile.read() # reading the file
finally: # the file will always be closed
afile.close()
print("after try")
# Now 'with' is recommended.
import sys print(sys.exc_info()) # return (type, value, traceback) # Return information about the most recent exception caught by an except # clause in the current stack frame or in an older stack frame.
Exception groups are used when it is necessary to raise multiple unrelated exceptions. They are part of the exception hierarchy so they can be handled with except like all other exceptions. In addition, they are recognised by except*, which matches their subgroups based on the types of the contained exceptions.
>>> try:
... raise ExceptionGroup("eg",
... [ValueError(1), TypeError(2), OSError(3), OSError(4)])
... except* TypeError as e:
... print(f'caught {type(e)} with nested {e.exceptions}')
... except* OSError as e:
... print(f'caught {type(e)} with nested {e.exceptions}')
...
# caught <class 'ExceptionGroup'> with nested (TypeError(2),)
# caught <class 'ExceptionGroup'> with nested (OSError(3), OSError(4))
# + Exception Group Traceback (most recent call last):
# | File "<stdin>", line 2, in <module>
# | ExceptionGroup: eg
# +-+---------------- 1 ----------------
# | ValueError: 1
# +------------------------------------
# Py2 and Py3 compatibility.
try:
input = raw_input # input() in Py2 is slow and dangerous
except NameError: # we are in Py3
pass
# Py2 and Py3 compatibility.
try:
integer_types = (int, long)
except NameError: # we are in Py3
integer_types = (int,)
# Usage: isinstance(variable, integer_types)
# Interactions with users.
while True:
reply = input("Enter int: ") # Py3
try:
value = int(reply)
except ValueError:
print("This is not int!")
else:
break
print("value is set to {}".format(value))