1.打印异常信息
try:open("abc.txt", 'r')print(a)except BaseException as msg:print(msg)
输出结果为:[Errno 2] No such file or directory: 'abc.txt'
2.常见的异常类型
3.异常用法
(1)try--except--else:except异常执行,else非异常执行
try:print(a)except NameError as msg:print(msg)else:print("没有异常时执行")
输出结果为:name 'a' is not defined
(2)try--except--finally:except异常执行,finally正常异常都执行
通过用于:文件的关闭,锁的释放,把数据库连接返还给连接池。
try:print(a)except NameError as msg:print(msg)finally:print("不管是否出现异常,都会被执行")
输出结果为:
name 'a' is not defined
不管是否出现异常,都会被执行
4.抛出异常
raise关键字:可用来抛出一个异常信息。只能使用Python提供的异常类。如果想要raise使用自定义异常类,则自定义类需要继承Exception类
e.g:
def say_hello(name=None):# name为空,抛出异常if name is None:raise NameError('"name" cannot be empty')else:print("hello, %s" % name)if __name__ == '__main__':say_hello()
运行say_hello的结果为: