python14异常处理

python

def test_div(num1,num2):

return num1 / num2

if __name__ == "__main__":

try:

print(test_div(5,"a"))

except ZeroDivisionError:

print("除数不能为零")

except TypeError as err:

print("输入数字")

print(err)

结果:

输入数字

unsupported operand type(s) for /: 'int' and 'str'

def test_file():

try:

f = open("test.txt","r")

rest = f.read()

print(rest)

except:

print("eror")

finally:

try:#加入新得try,防止文件没有被打开而需要关闭所产生的异常

f.close()

print("quan")

except:

pass

#try:

if __name__ == "__main__":

test_file()

class ApiException(Exception):

"""我的自定义异常"""

err_code = ""

err_msg = ""

def __init__(self, err_code=None, err_msg=None):

#111111如果存在则使用自己,要不就使用传进来的参数

self.err_code = self.err_code if self.err_code else err_code

self.err_msg = self.err_msg if self.err_msg else err_msg

def __str__(self):

return "Error:{0} - {1}".format(self.err_code,self.err_msg)

class InvalidCtrlexec( ApiException):

err_code = "4001"

err_msg = "bbbbb"

class BagException(ApiException):

err_code = "4002"

err_msg = "quanzhiqiang"

def test_exec(num1,num2):

"""除法的实习"""

#两个数必须为整数

if not isinstance(num1,int) or not isinstance(num2,int):

raise BagException()#BagException("88","9999")也是一样的输出,因为11111

if num2 == 0:

raise ApiException("40002","ccccc")

return num1 / num2

if __name__ == "__main__":

try:

rest = test_exec(5,"2")

"""

当为(5,0)结果:处处哦

Error:40002 - ccccc

当为(5,”quan”)结果为:

quanqqqq

Error:4002 - quanzhiqiang

"""

print(rest)

except BagException as B_err: #因为这个BagException是ApiException的子类,捕获小的再捕获大范围的

print("quanqqqq")

print(B_err)

except ApiException as err:

print("处处哦")

print(err)

class MyException(Exception):

pass

def v_for():

for i in range(1,100):

if i == 20:

raise MyException

print(i)

def call_v_for():

print("aaaaaaaaaaaaaaaa")

v_for()

print("bbbbbbbbbbbbbbb")

def test_raise():

print("ceshi")

try:

call_v_for()

except MyException:

print("88888888888888888")

print("endend")

if __name__ == "__main__":

test_raise()

结果:

ceshi

aaaaaaaaaaaaaaaa

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

88888888888888888

endend

因为异常是由原函数触发,如果没有捕获,就会一层一层往调用函数传递

这里在最外层捕获,所以call_v_for里面没有 print("bbbbbbbbbbbbbbb")

以上是 python14异常处理 的全部内容, 来源链接: utcz.com/z/386749.html

回到顶部