try:print('try start')
res =1/0print('try finish')except ZeroDivisionError as e:print(e)except Exception as e:# 可以有多个exceptprint('this is a public exctept, bug is :%s'% e)
方法二
try:print('try start')
res =1/0print('try finish')except(ZeroDivisionError,Excception)as e:print(e)
实战
#!/usr/bin/python3# -*- coding: utf-8 -*-# @Time : 2021/8/16 21:41# @Author : InsaneLoafer# @File : try_init.pydefupper(str_data):
new_str ='None'try:
new_str = str_data.upper()except Exception as e:print('程序出错了:{}'.format(e))return new_str
result = upper(1)# 如果没有try会抛出异常:AttributeError: 'int' object has no attribute 'upper'print('result:', result)deftest():try:print('collo')1/0print('hello')# 出错代码后面的代码不会执行except ZeroDivisionError as e:print(e)
test()deftest1():try:print('hello')print(name)except(ZeroDivisionError, NameError)as e:# 捕获的异常类型不对,也会报错,可以使用元组来定义多个异常类型print(e)print(type(e))print(dir(e))
test1()
程序出错了:'int' object has no attribute 'upper'
result: None
collo
division by zero
hello
name 'name' is not defined
<class 'NameError'>
['__cause__', '__class__', '__context__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__suppress_context__', '__traceback__', 'args', 'with_traceback']
Process finished with exit code 0