1.认识异常
程序执行时会抛出异常
open('abc','r')
# 结果
Traceback (most recent call last):
File "F:/Pycharm/pyselenium/ExceptionObj.py", line 1, in <module>
open('abc','r')
FileNotFoundError: [Errno 2] No such file or directory: 'abc'
如果知道报错类型为FileNotFoundError,我们可捕捉异常
try:
open('abc', 'r')
except FileNotFoundError:
print('异常了')
# 结果
异常了
如果程序报错不是FileNotFoundError类型,仍会抛出异常
try:
print(a)
except FileNotFoundError:
print('异常了')
# 结果
Traceback (most recent call last):
File "F:/Pycharm/pyselenium/ExceptionObj.py", line 9, in <module>
print(a)
NameError: name 'a' is not defined
若不知异常类型,可捕捉基类BaseException
try:
open('abc', 'r')
print(a)
except BaseException as msg:
print(msg)
# 结果
[Errno 2] No such file or directory: 'abc'
2.raise抛出异常
可使用raise自定义抛出的异常
def say_hello(name=None):
if name is None:
raise NameError('"name" cannot be empty')
else:
print('hello %s'%name)
say_hello()
# 结果
Traceback (most recent call last):
File "F:/Pycharm/pyselenium/ExceptionObj.py", line 31, in <module>
say_hello()
File "F:/Pycharm/pyselenium/ExceptionObj.py", line 26, in say_hello
raise NameError('"name" cannot be empty')
NameError: "name" cannot be empty
捕捉NameError
def say_hello(name=None):
if name is None:
raise NameError('"name" cannot be empty')
else:
print('hello %s'%name)
try:
say_hello()
except NameError as msg:
print(msg)
# 结果
"name" cannot be empty
注:raise只能使用python提供的异常类。如果想用raise使用自定义异常类,则自定义异常类需要继承Exception类。