异常的语法
try: <代码块1>被try关键字检查并保护的业务代码 except: <异常的类型>: <代码块2> #代码块1出现错误后执行的代码块
# coding:utf-8 def upper(str_data): new_str = '' try: new_str = str_data.upper() except: print('程序出错了') return new_str result = upper(1) print("result: ", result)
无法确定是哪种异常的情况下使用的捕获方法
try: <代码块> except Exception as e: <异常代码块>
def upper(str_data): new_str = '' try: new_str = str_data.upper() except Exception as e: print('程序出错了:{}'.format(e)) return new_str result = upper(1) print("result: ", result)
运行结果:
try: 1/0 except ZeroDivisionError as e: print(e)
def test(): try: print('111') 1/0 print('hello') except ZeroDivisionError as e: print(e) test()
运行结果:
捕获多种异常的写法1
try: print('try start') res = 1/0 print('try finish') except ZeroDivision Error as e: print(e) except Exception as e: # 可以有多个except print('This is a pubic except, bug is: %s' %e)
捕获异常的写法2
try: print('try start') res = 1/0 print('try finish') except(ZeroDivisionError, Exception) as e: print(e)
def test1(): try: print('hello') print(name) except (ZeroDivisionError, Exception) as e: print(e) print(type(e)) print(dir(e)) test1()
运行结果: