异常

作者: qianlong21st | 来源:发表于2018-05-18 15:12 被阅读0次

1常见异常类

异常通过raise语句来触发,自定义异常形式为class SomeCustomException(Exception): pass,此外可以自己重定义异常中的方法。

>>> 1/0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
>>> raise Exception("Error Info")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
Exception: Error Info
>>>

2 捕获异常try....except

try:
    x=int(input("input  one int num:"))
    y=int(input("input divider:"))
    print("{}/{}={}".format(x,y,x/y))
except ZeroDivisionError:
    print("y can't be zero")

3 异常的传播

3.1 except子句中使用raise来传递该异常

#ValueError("Value Error") from Exception("Exception Info")
try:
    1/0
except ZeroDivisionError:
    raise 
E:\henry\Python\venv\Scripts\python.exe E:/henry/Python/Exception.py
Traceback (most recent call last):
  File "E:/henry/Python/Exception.py", line 33, in <module>
    1/0
ZeroDivisionError: division by zero

Process finished with exit code 1

3.2 except子句中使用raise AnotherException来引起别的异常

try:
    1/0
except ZeroDivisionError:
    raise ValueError("Value Error")
E:\henry\Python\venv\Scripts\python.exe E:/henry/Python/Exception.py
Traceback (most recent call last):
  File "E:/henry/Python/Exception.py", line 33, in <module>
    1/0
ZeroDivisionError: division by zero

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "E:/henry/Python/Exception.py", line 35, in <module>
    raise ValueError("Value Error")
ValueError: Value Error

3.3 raise …from …

使用raise … from None来禁用异常上下文:

try:
    1/0
except ZeroDivisionError:
    raise ValueError("Value Error") from None

E:\henry\Python\venv\Scripts\python.exe E:/henry/Python/Exception.py
Traceback (most recent call last):
  File "E:/henry/Python/Exception.py", line 35, in <module>
    raise ValueError("Value Error") from None
ValueError: Value Error

使用raise…from…来自定义异常上下文:

try:
    1/0
except ZeroDivisionError:
    raise ValueError("Value Error") from Exception("Exception Info")

E:\henry\Python\venv\Scripts\python.exe E:/henry/Python/Exception.py
Exception: Exception Info

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "E:/henry/Python/Exception.py", line 35, in <module>
    raise ValueError("Value Error") from Exception("Exception Info")
ValueError: Value Error

3.4 多个except子句来处理异常

将字符串作为除数或被除数时会引发TypeError异常。

try:
    x=input("input  one int num:")
    y=input("input divider:")
    print("{}/{}={}".format(x,y,x/y))
except ZeroDivisionError:
    print("y can't be zero")
except TypeError:
    print("you should input one number ranther than one string")

3.5 使用(except1,except2,…)来同时处理多个异常

try:
    x=input("input  one int num:")
    y=input("input divider:")
    print("{}/{}={}".format(x,y,x/y))
except (ZeroDivisionError,TypeError):
    print("Error Input")

3.6 捕获对象

try:
    x=input("input  one int num:")
    y=input("input divider:")
    print("{}/{}={}".format(x,y,x/y))
except (ZeroDivisionError,TypeError) as e:
    print(e)

3.7 try...except...else

在没有出现异常时执行一个else子句

while True:
    try:
        x=int(input("Enter the first num:"))
        y=int(input("Enter the second num:"))
        val=x/y
        print("x/y is",val)
    except Exception as e:  #存在异常时会重新输入数字
        print("Error Input:",e)
        print("Try again!!!")
    else:   #没有异常时会进入此处执行
        break

3.8 finally子句

无论是否存在异常,均会执行finally子句,finally子句中适合执行一些清理工作(如关闭套接字等)。

while True:
    try:
        x=int(input("Enter the first num:"))
        y=int(input("Enter the second num:"))
        val=x/y
        print("x/y is",val)
    except Exception as e:  #存在异常时会重新输入数字
        print("Error Input:",e)
        print("Try again!!!")
    else:   #没有异常时会进入此处执行
        break
    finally:    #无论是否存在异常,均会执行finallly子句
        print("clean up")

4 警告

如果你只想发出警告,指出情况偏离了正轨,可使用模块warnings中的函数warn。

>>> from warnings import warn
>>> warn("I've got a bad feeling about this.")
__main__:1: UserWarning: I've got a bad feeling about this.
>>>

如果其他代码在使用你的模块,可使用模块warnings中的函数filterwarnings来抑制你发出的警告(或特定类型的警告),并指定要采取的措施,如"error"或"ignore"。

>>> from warnings import filterwarnings
>>> filterwarnings("ignore")
>>> warn("Anyone out there?")
>>> filterwarnings("error")
>>> warn("Something is very wrong!")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UserWarning: Something is very wrong!

如你所见,引发的异常为UserWarning。发出警告时,可指定将引发的异常(即警告类别),但必须是Warning的子类。如果将警告转换为错误,将使用你指定的异常。另外,还可根据异常来过滤掉特定类型的警告。

>>> filterwarnings("error")
>>> warn("This function is really old...", DeprecationWarning)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
DeprecationWarning: This function is really old...
>>> filterwarnings("ignore", category=DeprecationWarning)
>>> warn("Another deprecation warning.", DeprecationWarning)
>>> warn("Something else.")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UserWarning: Something else.

相关文章

  • 异常和模块

    异常 目标 了解异常 捕获异常 异常的else 异常finally 异常的传递 自定义异常 一. 了解异常 当检测...

  • python多线程

    异常基础知识 -异常简介: 运行时错误 -异常类: 异常数据 异常名称,异常数据,异常类型 -自定义异常 clas...

  • dart 异常

    dart中的异常 异常处理 抛出异常 异常捕获

  • Java基础之异常

    Java基础之异常 目录 异常简单介绍 ThrowableErrorException 异常分类 如何处理异常异常...

  • python核心编程-错误与异常

    本章主题:什么是异常Python中的异常探测和处理异常上下文管理引发异常断言标准异常创建异常相关模块 什么是异常 ...

  • motan(RPC)系统梳理知识点

    异常分类: 业务异常(bizException) 服务异常(serviceException) 框架异常(fram...

  • 异常

    Java异常体系 异常的分类 Java的异常分为两大类:Checked异常和Runtime异常(运行时异常)。所有...

  • 从零构架个人博客网站(二)-全局异常处理

    中间件的异常 全局异常中间件全局异常监听定义异常的返回结果定义常见的异常状态开发环境 异常查看 对于异常,我们可以...

  • Node.js异常处理

    Node.js异常分类: 变量异常 函数异常 调用异常 变量异常 未定义变量 未包含对象 变量类型错误 函数异常 ...

  • python 异常

    异常 目标 异常的概念 捕获异常 异常的传递 抛出异常 01. 异常的概念 程序在运行时,如果 Python 解释...

网友评论

      本文标题:异常

      本文链接:https://www.haomeiwen.com/subject/jajgdftx.html