class RadiusInputError(Exception):
pass
class Circle:
try:
def __init__(self, radius):
if isinstance(radius, int):
pass
else:
raise RadiusInputError
self.radius = radius
except RadiusInputError:
print('Radius is not a number')
c1 = Circle('hello')
当将非整数值作为半径传递但代码显示以下错误时,代码应执行except块:
Traceback (most recent call last):
File "D:/Pycharm Projects/HelloWorld/HandsOn10.py", line 17, in <module>
c1 = Circle('hello')
File "D:/Pycharm Projects/HelloWorld/HandsOn10.py", line 11, in __init__
raise RadiusInputError
__main__.RadiusInputError
答案 0 :(得分:0)
问题在于try/except
块将只执行一次-在此类的定义中:
class Circle:
try:
# try to define this method
def __init__(self, radius):
if isinstance(radius, int):
pass
else:
raise RadiusInputError
self.radius = radius
# if we got here, the method has been defined successfully!
except RadiusInputError:
# if we got here, an exception occurred WHILE DEFINING THE METHOD
print('Radius is not a number')
此代码丝毫不会影响对Circle.__init__
的调用。
您可以在此处查看其工作原理:
>>> class Test:
... print("before definition")
... def __init__(self):
... print("inside __self__")
... print("after definition - bye!")
...
before definition
after definition - bye!
>>> Test()
inside __self__
<__main__.Test object at 0x103541438>
>>>
您必须在呼叫站点处理异常:
class Circle:
def __init__(self, radius):
if not isinstance(radius, int):
raise RadiusInputError("Wrong radius!")
self.radius = radius
try:
c1 = Circle('hello')
except RadiusInputError as err:
print(f"Oops, something went wring: {err}"!)
答案 1 :(得分:0)
您将__init__()
函数声明包装在try/except
块中,但是函数声明不能引发异常。
您应该考虑以下其中一项:
__init__
函数的内容包装在try/except
中:class Circle:
def __init__(self, radius):
try:
if isinstance(radius, int):
pass
else:
raise RadiusInputError
self.radius = radius
except RadiusInputError:
print('Radius is not a number')
class Circle:
def __init__(self, radius):
if isinstance(radius, int):
pass
else:
raise RadiusInputError
self.radius = radius
try:
c1 = Circle('hello')
except RadiusInputError:
print('Radius is not a number')