Java自学者论坛

 找回密码
 立即注册

手机号码,快捷登录

恭喜Java自学者论坛(https://www.javazxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,会员资料板块,购买链接:点击进入购买VIP会员

JAVA高级面试进阶训练营视频教程

Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程Go语言视频零基础入门到精通Java架构师3期(课件+源码)
Java开发全终端实战租房项目视频教程SpringBoot2.X入门到高级使用教程大数据培训第六期全套视频教程深度学习(CNN RNN GAN)算法原理Java亿级流量电商系统视频教程
互联网架构师视频教程年薪50万Spark2.0从入门到精通年薪50万!人工智能学习路线教程年薪50万大数据入门到精通学习路线年薪50万机器学习入门到精通教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程MySQL入门到精通教程
查看: 633|回复: 0

python——异常类型

[复制链接]
  • TA的每日心情
    奋斗
    2024-11-24 15:47
  • 签到天数: 804 天

    [LV.10]以坛为家III

    2053

    主题

    2111

    帖子

    72万

    积分

    管理员

    Rank: 9Rank: 9Rank: 9

    积分
    726782
    发表于 2021-4-28 09:16:07 | 显示全部楼层 |阅读模式

    捕获异常try...except...finally...else

    python为高级语言,就是通过try...except...finally...else机制来处理错误。

    让我们来看一下这段错误代码:

    1 try2     print("try...")
    3     s = 10/0 #异常,之后代码不执行
    4     print("not run this code")
    5 except ZeroDivisonError as e: #有错误执行一下语句
    6     print("except",e)
    7 finally:
    8     print("finally...") # 有没有错误都要执行finally;此处可以不加
    9 print("END")
    ZeroDivisionError

    try下加入要执行代码,如果代码某处发生错误,错误之后代码段不执行直接跳到except捕获的错误类型抛出错误提示,最后走finally执行完毕,这里finally可有可无。else没有错误发生时执行。

    如果你不知道执行代码段可能发生什么种类的错误,可以捕获全部错误,比如:

    1 try2     f = open("unexsit.file","r") 
    3     f.read()
    4 except Exception as e:
    5     print("出错了,但是什么类型呢,打印一下吧",e)
    6 
    7 #[Errno 2] No such file or directory: unexsit.file
    Exception

     常见错误类

    AttributeError 不存在属性

    IoError  输入或输出异常

    ImportError 无法引入模块或包。(一般是路径问题或模块名称有误)

    IndentationError 语法错误(SyntaxError子类),一般是代码缩进错误

    KeyError 字典中不存在关键字

    KeyboardInterrupt Ctrl+C被按下

    NameError 使用一个未被赋予对象的变量

    SyntaxError 语法错误

    TypeError 传入对象类型与要求不符

    UnboundLocalError 变量作用域的问题(详见:https://docs.python.org/2/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value)

     1 x=9
     2 
     3 def test():
     4     print(x)#
     5     x =1#python从上到下解释,会吧x当做局部变量,然而上边print要打印未声明的局部变量,报错
     6 
     7 test()
     8 #UnboundLocalError: local variable 'x' referenced before assignment
     9 //修改
    10 x=9
    11 def test():
    12     global x
    13     print(x)
    14     x =1
    15 
    16 test()
    UnboundLocalError

    官方解释法:

     1 It can be a surprise to get the UnboundLocalError in previously working code when it is modified by adding an assignment statement somewhere in the body of a function.
     2 
     3 This code:
     4 
     5 >>>
     6 >>> x = 10
     7 >>> def bar():
     8 ...     print x
     9 >>> bar()
    10 10
    11 works, but this code:
    12 
    13 >>>
    14 >>> x = 10
    15 >>> def foo():
    16 ...     print x
    17 ...     x += 1
    18 results in an UnboundLocalError:
    19 
    20 >>>
    21 >>> foo()
    22 Traceback (most recent call last):
    23   ...
    24 UnboundLocalError: local variable 'x' referenced before assignment
    25 This is because when you make an assignment to a variable in a scope, that variable becomes local to that scope and shadows any similarly named variable in the outer scope. Since the last statement in foo assigns a new value to x, the compiler recognizes it as a local variable. Consequently when the earlier print x attempts to print the uninitialized local variable and an error results.
    26 
    27 In the example above you can access the outer scope variable by declaring it global:
    28 
    29 >>>
    30 >>> x = 10
    31 >>> def foobar():
    32 ...     global x
    33 ...     print x
    34 ...     x += 1
    35 >>> foobar()
    36 10
    37 This explicit declaration is required in order to remind you that (unlike the superficially analogous situation with class and instance variables) you are actually modifying the value of the variable in the outer scope:
    38 
    39 >>>
    40 >>> print x
    41 11
    官方

    ValueError 传入不期望值

    自定义异常

    自定义异常通过继承异常基类的方法的派生类。(好绕嘴)如下:

     1 class MyException(Exception):
     2     def __init__(self,name):
     3         self.msg = name
     4 
     5     def __str__(self):
     6        return self.msg # 可以不重写,继承基类
     7 
     8 #调用
     9 try:
    10     if flag:
    11         pass
    12     else:
    13         raise MyException("自定义错误")
    14 except MyException as e:
    15     print(e)
    自定义异常

     

    哎...今天够累的,签到来了1...
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|手机版|小黑屋|Java自学者论坛 ( 声明:本站文章及资料整理自互联网,用于Java自学者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

    GMT+8, 2024-12-22 22:51 , Processed in 0.059688 second(s), 27 queries .

    Powered by Discuz! X3.4

    Copyright © 2001-2021, Tencent Cloud.

    快速回复 返回顶部 返回列表