在python中断言后如何继续执行程序?

Ele*_*tio 5 python python-2.7 python-3.x

我正在 python 中学习异常,我有一些疑问:

我们可以在 raise 中使用任何名称作为错误吗?

就像我读过的,当您使用 raise 时,您必须定义错误类型,所以我不能使用任何字符串名称作为错误吗?喜欢SkienaError或者我必须记住所有错误类型并且必须只使用那些错误类型名称?

    a=int(input())
if a!=10:
    raise SkienaError
else:
    print(a,"pp")
Run Code Online (Sandbox Code Playgroud)

第二个疑问是假设我希望用户应该输入 int 但他输入字符串所以一个断言弹出但我希望程序应该继续而不终止并再次要求输入直到用户提供 int 类型输入,我不想在这里使用 while 循环我想知道在 python 中使用 raise 或 assert 是否可能?喜欢:

a=int(input())
assert type(a)==int
print(a,"hello")
Run Code Online (Sandbox Code Playgroud)

因此,如果用户给出 str 类型的输入,那么程序是否有可能不断给出错误并询问新的输入,直到输入类型为 int。

Jor*_*een 8

为了使您自己的例外,您必须创建它。

例如

class MyAppLookupError(LookupError):
'''raise this when there's a lookup error for my app'''
Run Code Online (Sandbox Code Playgroud)

要在抛出异常后继续执行,请执行以下操作:

a = 5
try:
    assert a == 5
except AssertionError as e:
    print(e)
Run Code Online (Sandbox Code Playgroud)

一个try块将尝试执行一个代码块。如果发生异常,它将执行该except块。