Python Day-例外处理

花韻仙語
发布: 2025-02-04 18:40:15
转载
392人浏览过

例外处理

- >例外是一个异常事件,发生在程序执行过程中,并突然停止程序(立即)
> ->异常处理允许响应错误,而不是崩溃运行程序。

语法:>

    try:
          # code that might raise an exception
    except someexception:
          # code to handle the exception
    else:
         # code to run if no exception occurs
    finally:
        # code to run regardless of whether an exception occurs

登录后复制

尝试,除了,否则,最后阻止

>

1。尝试块

try块包含可能引起异常的代码。
    >
  • 如果发生异常,则将其传递给块。
  • 2。除了block

  • block处理在try块中发生的异常。
  • >您可以指定不同类型的异常,也可以使用一般条款以捕获所有异常。

  • 3。 else block(可选)
  • 仅在try块中出现无例外的情况。

4。最后阻止(可选)

  • 最终块执行,无论是否出现异常。
  • >
>通常用于清理操作,例如关闭文件或释放资源。>

>示例:

    >
  • 1)
  • try:
        no1 = int(input("enter no."))
        no2 = int(input("enter no. "))
        print(no1//no2)
    except zerodivisionerror:
        print("no2 should not be zero. check no2 value ")
    print(no1+no2)
    
    登录后复制
  • >输出:

enter no.10
enter no. 0
no2 should not be zero. check no2 value 
10
登录后复制
2)

try:
    no1 = int(input("enter no."))
    no2 = int(input("enter no. "))
    print(no1//no2)
    print(no1+no2)
except zerodivisionerror:
    print("no2 should not be zero. check no2 value ")
except valueerror:
    print("inputs should be numbers ")
登录后复制

>输出:

enter no.10
enter no. ten
inputs should be numbers
登录后复制

3)

try:
    no1 = int(input("enter no."))
    no2 = int(input("enter no. "))
    print(no1//no2)
    print(no1+no2)
    f = open("pqrs.txt")
except zerodivisionerror:
    print("no2 should not be zero. check no2 value ")
except valueerror:
    print("inputs should be numbers ")
except:
    print("something went wrong")
登录后复制

>输出:

#if all inputs are correct
enter no.10
enter no. 5
2
15

#if any error not specified particularly
enter no.10
enter no. 5
2
15
something went wrong

#if zerodivisionerror
enter no.10
enter no. 0
no2 should not be zero. check no2 value

#if valueerror
enter no.10
enter no. ten
inputs should be numbers 
登录后复制
异常处理和条件语句之间的区别


>


**注意:**
- 处理不可预测的错误时,请使用try-exce ->处理预期条件时使用if-else

追溯模块:

python中的追溯模块用于提取,格式和打印错误跟踪信息,有助于调试和日志记录异常。

image description


>示例:1

import traceback
try:
    no1 = int(input("enter no."))
    no2 = int(input("enter no. "))
    print(no1//no2)
    print(no1+no2)
    f = open("pqrs.txt")
    print(f.read())
except (valueerror, zerodivisionerror) as msg:
    print("check ",msg)

except:
    print("something went wrong")
    traceback.print_exc()
登录后复制

>输出:

enter no.10
enter no. 0
check  integer division or modulo by zero
登录后复制

>示例:2

import traceback
try:
    no1 = int(input("enter no."))
    no2 = int(input("enter no. "))
    print(no1//no2)
    print(no1+no2)
    f = open("pqrs.txt")
    print(f.read())
except (valueerror, zerodivisionerror) as msg:
    print("check ",msg)
except:
    print("something went wrong")
    traceback.print_exc()
finally:
    print("check finally message")
登录后复制

>输出:image description

enter no.10
enter no. 10
1
20
something went wrong
traceback (most recent call last):
  file "/home/guru/desktop/guru/python/user.py", line 7, in <module>
    f = open("pqrs.txt")
        ^^^^^^^^^^^^^^^^
filenotfounderror: [errno 2] no such file or directory: 'pqrs.txt'
check finally message
登录后复制


捕获多个特定异常:

> ->我们可以在单个单个中处理多个异常,除了使用元组。
->使用,因为我们也可以为异常提供一个可变名称。

>

trackback.print_exc():它提供详细的错误信息(行号,错误类型,消息)。

糟糕:


>显示对象的存储器位置:

class employee:
    pass

emp1 = employee()
emp2 = employee()
print(emp1)
print(emp2)
登录后复制

>输出:

<__main__.employee object at 0x730a36434110>
<__main__.employee object at 0x730a36434080>
登录后复制

pass关键字的意思是“无所事事”(占位符),因此该类目前为空(它没有属性或方法)。

__ doc __(docstring属性)

> __doc__属性用于访问类,功能,模块或方法的docstring。 docstring是一个多行字符串,提供有关对象的文档,该对象在triple引号('''''')中声明。 >示例:

class employee:
    '''this class is for creating employees'''
print(employee.__doc__)
登录后复制

>输出:


4

this class is for creating employees
登录后复制

自我关键字:

立即学习Python免费学习笔记(深入)”;

->“ self”用于访问和操纵类中的实例变量和方法。 -> self代表类的实例。>

>特定对象的


- 使用self.variable_name定义的>。 ->对于每个对象唯一。

>

>示例:1

class employee:
    def work(self):
        print(self.empname, self.job_nature)

emp1 = employee()
emp1.empname = 'guru'
emp1.job_nature = "designing"
emp2 = employee()
emp2.empname = "pritha"
emp2.job_nature = "development"
emp1.work()
emp2.work()
登录后复制

>输出:

guru designing
pritha development
登录后复制

>示例:2类,带3种方法:

class employee:
    organization = "infosys"
    def work(self):
        print(self.empname, self.job_nature, self.organization)
    def take_leave(self):
        pass
    def promote(self):
        pass

emp1 = employee()
emp1.empname = 'guru'
emp1.job_nature = "designing"
emp2 = employee()
emp2.empname = "pritha"
emp2.job_nature = "development"
emp1.work()
emp2.work()
登录后复制

>输出:

guru designing infosys
pritha development infosys
登录后复制
登录后复制

类特定信息:
类别的信息是指在类的所有实例(对象)之间共享的数据。

>示例:

class employee:
    def work(self):
        print(self.empname, self.job_nature, self.organization)

    def take_leave(self):
        pass

    def promote(self):
        pass

emp1 = employee()
emp1.empname = 'guru'
emp1.job_nature = "designing"
emp2 = employee()
emp2.empname = "pritha"
emp2.job_nature = "development"
employee.organization = "infosys"
emp1.work()
emp2.work()
登录后复制

>输出:

guru designing infosys
pritha development infosys
登录后复制
登录后复制


以上就是Python Day-例外处理的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:dev.to网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号