/ / Python - простий спосіб зафіксувати виняток у try-osim-else - python

Python - простий спосіб зафіксувати виняток у try-except-else - python

У Python ми можемо використовувати as для захоплення екземпляра виключення в except заява. Однак, схоже, не існує простого способу зробити те ж саме в else заява після try. Щоб було більш зрозуміло, дивіться код нижче.

try:
raise Exception("Foo")
except ValueError as valueError:
print(valueError)
print("I can capture the exception instance with "as" keyword")
else:    # Cannot use "as" here
print("Some exception other than ValueError")
print("How can I capture the exception in order to, e.g. print its message?")

Будь ідея?

Відповіді:

4 для відповіді № 1
try:
raise Exception("Foo")
except ValueError as valueError:
print(valueError)
print("I can capture the exception instance with "as" keyword")
except Exception as e:
print(e)
print("Some exception other than ValueError")
else:
print("no exception raised")

4 для відповіді № 2

Використовуйте кілька except статті:

Або так:

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 (RuntimeError, TypeError, NameError):
pass