Python基础之异常处理

发布时间:2021-12-03 公开文章

I am not a designer nor a coder. I'm just a guy with a point-of-view and a computer.

 

筑基<融合<元婴<分神<渡劫<大乘

 

#使用try/except语句
tp = 25, 67, 12 #元组
try:
    print(tp[3])
except Exception:
    print('索引超出边界值')
索引超出边界值
#try/except语句...Exception捕捉所有异常
tp = 25, 67, 12 #元组
try:
    print(tp[3])
except IndexError as err:
    print('错误:', err)
错误: tuple index out of range
#使用try/except语句捕捉索引超出边界值
tp = 25, 67, 12, 64 #元组
def getIndex(num):
    #try/except语句
    try:    
        return (tp[num])
    except IndexError as ex:        
        print("错误: {0}".format(ex))
        #print('Index', arg)
x = 0
x = int(input('输入索引返回元素:'))
print('Tuple Element:', getIndex(x))
输入索引返回元素:3
Tuple Element: 64
#try/except语句,使用sys.exc_info()
import sys
tp = 25, 67, 12 #元组
try:
    print(tp(3)) #应用中括号tp[3],却使用tp(3)
except IndexError as err:
    print('错误:', err)    
except: #可拦截取所有异常,放在所有except语句的最后
    print('错误:{0[0]}\n {0[1]}\n {0[2]}'.format(
        sys.exc_info()))
错误:<class 'TypeError'>
 'tuple' object is not callable
 <traceback object at 0x000002C24814C8C8>
# try/except/else语句
num1, num2 = eval(
        input('请输入两个数值,用逗号隔开:'))
try:
    result = num1 / num2
except ZeroDivisionError as err:
     print('Error:', err)
else:
    print('相除结果:', result)
请输入两个数值,用逗号隔开:2,0
Error: division by zero
# try/finally语句
def func(num1, num2):
    try:
        result = num1 // num2
        print('Result:', result)
    finally:        
        print('完成计算')        

func(151, 12) #可得结果
# func(1, 0) #引发异常
Result: 12
完成计算
# try/exception/finally语句

def demo(num1, num2):
    try:
        result = divmod(num1, num2)
    except ZeroDivisionError as err:
        print('错误', err)
    else:
        print('计算结果', result)
    finally:
        print('完成计算')

one, two = eval(
        input('请输入两个数值,用逗号隔开:'))
demo(one, two)
请输入两个数值,用逗号隔开:2,0
错误 integer division or modulo by zero
完成计算
# raise语句 配合内建异常类
import math
# 定义函数
def calcArea(radius):
    if radius < 0:
        raise RuntimeError("不能输入负值") # 推荐
    else:
        area = radius * radius * math.pi
        return area
#调用函数
value = float(input('请输入数值: '))
circleArea = calcArea(value)
print('圆面积', circleArea)
请输入数值: 2
圆面积 12.566370614359172
# try/except 配合 raise语句
try:
    raise Exception('引发错误')
except Exception as err:
    print(err)
else:
    print('没有错误')
引发错误
# 在try/except语句使用 raise语句
def demo(data, num):    
    try:        
        data[num]     
    except IndexError as err:
        print(err)
        raise IndexError('索引超出边界值')
    else:
        print(data[num])
lt = ['Tom', 'Vicky', 'Steven']#List
demo(lt, 1)
# demo(lt, 3)
Vicky
#使用assert语句
data = [28, 67, 78]
def demo(data):
    total = 0
    for item in data:
        assert item > 0, '输入的值要大于零'    
        total += item
    return total
print('合计:', demo(data))
合计: 173
#自定义异常处理类
class MyError(Exception):
    def __init__(self, radius):        
        self.radius = radius
    def __str__(self):
        return repr(self.radius)
#定义一个圆形类
import math

class Circular:
    def __init__(self, radius):
        self.setR(radius)

    def getR(self): #获取半径值设为私有属性
        return self._radius

    def setR(self, radius): #设置半径值
        if radius > 0:
            self._radius = radius
        else:            
            raise MyError(radius)

    def periphery(self): #计算圆周长     
        return 2 * self._radius * math.pi

    def calcArea(self):        
        return self._radius * self._radius * math.pi

    def __repr__(self): #设置输出格式
        return '圆周长: {:4.3f}, 圆面积:{:4.3f}'.format(
            self.periphery(), self.calcArea())

try:
    one = Circular(15)#对象1
    print(one)
    two = Circular(-11)#对象2
    print(two)    
except MyError as err:
    print()
    print('引发异常, 错误值:', err.radius)
圆周长: 94.248, 圆面积:706.858

引发异常, 错误值: -11