zoukankan      html  css  js  c++  java
  • python_异常处理

    1.除数为0的异常处理

    i=input('请输入数字: ')
    n=888
    try:
    result=n/int(i)
    print(result)
    print('{0}除以{1}等于{2}'.format(n,i,result))
    except ZeroDivisionError as e:
    print('不能除以0,异常{}'.format(e))
    2.多个except代码块
    i=input('请输入数字: ')
    n=888
    try:
    result=n/int(i)
    print(result)
    print('{0}除以{1}等于{2}'.format(n,i,result))
    except ZeroDivisionError as e:
    print('不能除以0,异常{}'.format(e))
    except ValueError as e:
    print("输入的是无效数字,异常:{}".format(e))
    3.多重异常捕获
    i=input('请输入数字: ')
    n=888
    try:
    result=n/int(i)
    print(result)
    print('{0}除以{1}等于{2}'.format(n,i,result))
    except (ZeroDivisionError,ValueError) as e:
    print('异常{}'.format(e))
    4.try-except语句嵌套

    #coding=utf-8
    i=input("请输入数字: ")
    n=8888
    try:
    i2=int(i)
    try:
    result=n/i2
    print("{0}除以{1}等于{2}".format(n,i2,result))
    except ZeroDivisionError as e1:
    print("不能除以0,异常:{}".format(e1))
    except ValueError as e2:
    print("输入的是无效数字,异常:{}".format(e2))

    5.使用finally代码块释放资源

    i=input('请输入数字: ')
    n=888
    try:
    result=n/int(i)
    print(result)
    print('{0}除以{1}等于{2}'.format(n,i,result))
    except ZeroDivisionError as e:
    print('不能除以0,异常{}'.format(e))
    except ValueError as e:
    print("输入的是无效数字,异常:{}".format(e))
    finally:
    print('资源释放')
    6.自定义异常类
    class TestException(Exception):
    def __init__(self,message):
    super().__init__(message)

    i=input('请输入数字: ')
    n=888
    try:
    result=n/int(i)
    print(result)
    print('{0}除以{1}等于{2}'.format(n,i,result))
    except ZeroDivisionError as e:
    #print('不能除以0,异常{}'.format(e))
    raise TestException('不能除以0')
    except ValueError as e:
    #print("输入的是无效数字,异常:{}".format(e))
    raise TestException('输入的是无效数字')



  • 相关阅读:
    用js写留言信息的判断非空条件
    tp3.2中怎么访问分类及子分类下面的文章
    关于PHP中的 serialize () 和 unserialize () 的使用(即关于PHP中的值与已存储的表示的相互转换)
    iOS 8 Auto Layout界面自动布局系列2-使用Xcode的Interface Builder添加布局约束
    iOS深入学习(Block全面分析)
    面试4
    Android
    android适配不同分辨率的手机
    android分辨率适配
    Android屏幕适配全攻略(最权威的官方适配指导)
  • 原文地址:https://www.cnblogs.com/JacquelineQA/p/13199082.html
Copyright © 2011-2022 走看看