zoukankan      html  css  js  c++  java
  • 【Python】异常处理

    处理ZeroDivisionError异常

    下面看一种异常,除数为0的异常,我们都知道,当除数为0的时候是不可以运算的。

    print(5/0)
    image

    在上述Traceback中,已经指出的错误ZeroDivisionError是一个异常对象。Python无法按照你的要求做时,就会产生这种对象。

    1.1使用try-except代码块

    当你预先知道会发生这种错误时,可编写一个try-except代码块来处理可能发生的异常。你让python尝试运行一些代码,并告诉他如果这些代码引发了指定的异常,该怎么办

    try:
        print(5/0)
    except ZeroDivisionError:
        print("You can't divide by 0")

    运行结果:

    image

    1.2使用异常避免奔溃

    发生错误时,如果程序还没有工作完成,妥善的处理错误尤其重要,这种情况经常会出现在要求用户提供的主程序中,如果程序能够妥善的处理无效请求,就能再提示用户提供有效输入,而不至于奔溃

    下面是一个简易计算机

    print("Give me two number,I will divide them!")
    print("Enter the 'q' to quit!")
    
    while True:
        first_number = input("
    Enter the first number:")
        if first_number == 'q':
            break
        second_number = input("
    Enter the second number:")
        if int(second_number) == 0:
            second_number = input("
    You can't divide by 0,please re-Enter the second number:")
        if second_number == 'q':
            break
        answer = int(first_number)/int(second_number)
        print(answer)

    运行结果

    image

    当输入的分母为0时也做了相应处理,这种是使用if语句强行判断处理分母为0的情况,那么使用异常处理该如何处置呢?

    print("Give me two number,I will divide them!")
    print("Enter the 'q' to quit!")
    
    while True:
        first_number = input("
    Enter the first number:")
        if first_number == 'q':
            break
        second_number = input("
    Enter the second number:")
        if second_number == 'q':
            break
        try:
            answer = int(first_number)/int(second_number)
        except ZeroDivisionError:
            second_number = input("
    You can't divide by 0,please re-Enter the second number:")
            answer = int(first_number) / int(second_number)
            print(answer)
        else:
            print(answer)

    当除法产生异常的时候,就提示重新输入不为0的除数。

    处理FileNotFoundError异常

    file_path = "txtMyFavoriteFruit.txt"
    
    try:
        with open(file_path) as file_object:
            Contents = file_object.readlines()
            for line in Contents:
                print(line.strip())
    except FileNotFoundError:
        msg = "Sorry,the file " + file_path + " does not exist."
        print(msg)

    当文件存在时候,运行结果:

    image

    删除文件后的运行结果:

    image

  • 相关阅读:
    laravel、TP、YII框架的优缺点
    关于如何关闭Laravel中严格模式的两种方法
    Laravel扩展阿里云OSS对象存储
    Laravel权限管理的应用记录
    laravel原生MySQL之Group记录
    laravel导出Xlsx
    软件工程课的认识
    斗兽棋项目开发计划书
    斗兽棋测试计划说明书
    测试报告分析
  • 原文地址:https://www.cnblogs.com/OliverQin/p/7899176.html
Copyright © 2011-2022 走看看