Python AttributeError 异常

定义和用法

当尝试执行当前对象上不存在的属性或方法时,会引发 AttributeError 异常。

可以通过 try...except 语句捕获 AttributeError,参见以下示例。

实例

例子 1

如果尝试访问不存在的方法,将会引发 AttributeError

x = "Hello"
print(x.toUpperCase())

亲自试一试

例子 2:异常处理

使用 try...except 语句处理 AttributeError

x = "Hello"
try:
  print(x.toUpperCase())
except AttributeError:
  print("错误!字符串没有 toUpperCase 方法!")
except:
  print("发生了其他错误")

亲自试一试