搜索
首页后端开发Python教程python的错误与异常处理

python的错误与异常处理

Sep 30, 2018 pm 01:55 PM
python

本篇文章给大家带来的内容是关于python的错误与异常处理,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

一:语法错误syntax errors

熟悉语法!

二:异常

①打印错误信息时,异常的类型作为异常的内置名显示,并以调用栈的形式显示具体信息

②常见的异常:
            NameError、
            ZeropisionError、
            TypeError
            SyntaxError
            IndexError    索引超出序列范围
            KeyError    请求一个不存在的字典关键字
            IOError        输入输出错误
            AttributeError    尝试访问未知的对象属性
三:异常处理

while True:
try:
x = int(input("Please enter a number: "))
break
except ValueError:
print("Oops!  That was no valid number.  Try again   ")

try语句按照如下方式工作;
①首先,执行try子句(在关键字try和关键字except之间的语句)
②如果没有异常发生,忽略except子句,try子句执行后结束。
③如果在执行try子句的过程中发生了异常,那么try子句余下的部分将被忽略。
④如果异常的类型和 except 之后的名称相符,那么对应的except子句将被执行。最后执行 try 语句之后的代码。
⑤如果一个异常没有与任何的except匹配,那么这个异常将会传递给上层的try中。
⑥一个 try 语句可能包含多个except子句,分别来处理不同的特定的异常。最多只有一个分支会被执行。
⑦一个except子句可以同时处理多个异常,这些异常将被放在一个括号里成为一个元组。

except (RuntimeError, TypeError, NameError):
pass

⑧最后一个except子句可以忽略异常的名称,它将被当作通配符使用。你可以使用这种方法打印一个错误信息,然后再次把异常抛出。
⑨try except 语句还有一个可选的else子句,如果使用这个子句,那么必须放在所有的except子句之后。这个子句将在try子句没有发生任何异常的时候执行.

三:抛出异常

Python 使用 raise 语句抛出一个指定的异常
raise 唯一的一个参数指定了要被抛出的异常。
它必须是一个异常的实例或者是异常的类(也就是 Exception 的子类)

四:用户自定义异常

    可以通过创建一个新的异常类来拥有自己的异常。
    异常类继承自 Exception 类,可以直接继承,或者间接继承。
    当创建一个模块有可能抛出多种不同的异常时,
    一种通常的做法是为这个包建立一个基础异常类,

五:定义清理行为

try:
        raise KeyboardInterrupt
    finanlly:
        print("dooo")

    不管 try 子句里面有没有发生异常,finally 子句都会执行
    如果一个异常在 try 子句里(或者在 except 和 else 子句里)被抛出,
    而又没有任何的 except 把它截住,那么这个异常会在 finally 子句执行后再次被抛出

六:扩展------------->断言机制

    assert 等价于布尔真的判定,不满足抛出异常AssertionError
    用途:    防御性的程序
        运行时需要逻辑检查
    参考文献:《python使用断言的最佳时机》

# ---------------------------------------------------------------------#
# 异常处理
# ---------------------------------------------------------------------#
while True:
    try:
        x = int(input("Please enter a number: "))
        break
    except ValueError:
            print("Oops!  That was no valid number.  Try again   ")

# ---------------------------------------------------------------------#
# 抛出异常
# ---------------------------------------------------------------------#
"""
try:
    raise NameError('HiThere')
except NameError:
    print('An exception flew by!')
    raise
"""

# ---------------------------------------------------------------------#
# 用户自定义异常
# ---------------------------------------------------------------------#
class MyError(Exception):   # 继承自Exception
    def __init__(self, value):  # 构造函数重写
        self.value = value

    def __str__(self):
        return repr(self.value)
try:
    raise MyError(2*2)  # 抛出异常
except MyError as e:
        print('My exception occurred, value:', e.value)
# 当创建一个模块有可能抛出多种不同的异常时,
# 一种通常的做法是为这个包建立一个基础异常类,
# 然后基于这个基础类为不同的错误情况创建不同的子类
class Error(Exception):
    """Base class for exceptions in this module."""
    pass
class InputError(Error):
    """Exception raised for errors in the input.
    Attributes:
        expression -- input expression in which the error occurred
        message -- explanation of the error
    """
    def __init__(self, expression, message):
        self.expression = expression
        self.message = message
class TransitionError(Error):
    """Raised when an operation attempts a state transition that's not
    allowed.

    Attributes:
        previous -- state at beginning of transition
        next -- attempted new state
        message -- explanation of why the specific transition is not allowed
    """

    def __init__(self, previous, next1, message):
        self.previous = previous
        self.next = next1
        self.message = message


try:
    raise InputError(2*2, 45)   # 抛出异常
except InputError:         # 处理异常
        print('My exception occurred')

# ---------------------------------------------------------------------#
# 定义清理行为
# ---------------------------------------------------------------------#

def divide(x, y):
    try:
        result = x / y
    except ZeroDivisionError:
        print("division by zero!")
    else:                           # 没有异常的时执行
        print("result is", result)
    finally:                        # 无论在任何情况下都会执行的清理行为
        print("executing finally clause")


# 一个异常在 try 子句里(或者在 except 和 else 子句里)被抛出,
# 而又没有任何的 except 把它截住,那么这个异常会在 finally 子句执行后再次被抛出
# divide("2", "1")   #从测试代码

以上是python的错误与异常处理的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文转载于:博客园。如有侵权,请联系admin@php.cn删除
Python:编译器还是解释器?Python:编译器还是解释器?May 13, 2025 am 12:10 AM

Python是解释型语言,但也包含编译过程。1)Python代码先编译成字节码。2)字节码由Python虚拟机解释执行。3)这种混合机制使Python既灵活又高效,但执行速度不如完全编译型语言。

python用于循环与循环时:何时使用哪个?python用于循环与循环时:何时使用哪个?May 13, 2025 am 12:07 AM

useeAforloopWheniteratingOveraseQuenceOrforAspecificnumberoftimes; useAwhiLeLoopWhenconTinuingUntilAcIntiment.ForloopSareIdeAlforkNownsences,而WhileLeleLeleLeleLoopSituationSituationSituationsItuationSuationSituationswithUndEtermentersitations。

Python循环:最常见的错误Python循环:最常见的错误May 13, 2025 am 12:07 AM

pythonloopscanleadtoerrorslikeinfiniteloops,modifyingListsDuringteritation,逐个偏置,零indexingissues,andnestedloopineflinefficiencies

对于循环和python中的循环时:每个循环的优点是什么?对于循环和python中的循环时:每个循环的优点是什么?May 13, 2025 am 12:01 AM

forloopsareadvantageousforknowniterations and sequests,供应模拟性和可读性;而LileLoopSareIdealFordyNamicConcitionSandunknowniterations,提供ControloperRoverTermination.1)forloopsareperfectForeTectForeTerToratingOrtratingRiteratingOrtratingRitterlistlistslists,callings conspass,calplace,cal,ofstrings ofstrings,orstrings,orstrings,orstrings ofcces

Python:深入研究汇编和解释Python:深入研究汇编和解释May 12, 2025 am 12:14 AM

pythonisehybridmodelofcompilationand interpretation:1)thepythoninterspretercompilesourcececodeintoplatform- interpententbybytecode.2)thepytythonvirtualmachine(pvm)thenexecuteCutestestestesteSteSteSteSteSteSthisByTecode,BelancingEaseofuseWithPerformance。

Python是一种解释或编译语言,为什么重要?Python是一种解释或编译语言,为什么重要?May 12, 2025 am 12:09 AM

pythonisbothinterpretedAndCompiled.1)它的compiledTobyTecodeForportabilityAcrosplatforms.2)bytecodeisthenInterpreted,允许fordingfordforderynamictynamictymictymictymictyandrapiddefupment,尽管Ititmaybeslowerthananeflowerthanancompiledcompiledlanguages。

对于python中的循环时循环与循环:解释了关键差异对于python中的循环时循环与循环:解释了关键差异May 12, 2025 am 12:08 AM

在您的知识之际,而foroopsareideal insinAdvance中,而WhileLoopSareBetterForsituations则youneedtoloopuntilaconditionismet

循环时:实用指南循环时:实用指南May 12, 2025 am 12:07 AM

ForboopSareSusedwhenthentheneMberofiterationsiskNownInAdvance,而WhileLoopSareSareDestrationsDepportonAcondition.1)ForloopSareIdealForiteratingOverSequencesLikelistSorarrays.2)whileLeleLooleSuitableApeableableableableableableforscenarioscenarioswhereTheLeTheLeTheLeTeLoopContinusunuesuntilaspecificiccificcificCondond

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

WebStorm Mac版

WebStorm Mac版

好用的JavaScript开发工具

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

SecLists

SecLists

SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器