search
HomeBackend DevelopmentPython TutorialAnalysis of exception handling examples in Python

    ##1. What is an exception

    In python, the exceptions triggered by errors are as follows

    Analysis of exception handling examples in Python

    2. Types of exceptions

    Different exceptions in python can be identified by different types. An exception identifies an error.

    1. Common exception classes

    • AttributeError Trying to access a tree that does not have an object, such as foo.x, but foo has no attribute x

    • IOError Input/output exception; basically cannot open file

    • ImportError Unable to import module or package; basically path problem or wrong name

    • IndentationError Syntax error (subclass of); code is not properly aligned

    • IndexError The subscript index exceeds the sequence boundary, such as trying to access x when x has only three elements [5]

    • KeyError Attempting to access a key that does not exist in the dictionary

    • KeyboardInterrupt Ctrl C was pressed

    • NameError uses a variable that has not been assigned an object

    • SyntaxError The Python code is illegal and the code cannot be compiled (I personally think this is a syntax error and was written incorrectly)

    • TypeError The incoming object type does not meet the requirements

    • UnboundLocalError Trying to access a local variable that has not been set, basically because there is another one with the same name global variable, causing you to think you are accessing it

    • ValueError Passing in a value that the caller does not expect, even if the value is of the correct type

    2. Exception example:

    # TypeError:int类型不可迭代
    for i in 3:
        pass
    
    # ValueError
    num=input(">>: ") #输入hello
    int(num)
    
    # NameError
    aaa
    
    # IndexError
    l=['egon','aa']
    l[3]
    
    # KeyError
    dic={'name':'egon'}
    dic['age']
    
    # AttributeError
    class Foo:pass
    Foo.x
    
    # ZeroDivisionError:无法完成计算
    res1=1/0
    res2=1+'str'

    3. Exception handling

    1. Basic syntax try...except

    try:
        被检测的代码块
    except 异常类型:
        try中一旦检测到异常,就执行这个位置的逻辑

    Example

    try:
        f = [ 'a', 'a', 'a','a','a', 'a','a',]
        g = (line.strip() for line in f) #元组推导式
        print(next(g))
        print(next(g))
        print(next(g))
        print(next(g))
        print(next(g))
    except StopIteration:
        f.close()

    Exception class It can only be used to handle specified exceptions. Non-specified exceptions cannot be handled.

    s1 = 'hello'
    try:
        int(s1)
    except IndexError as e:  # 未捕获到异常,程序直接报错
        print(e)

    2. Multi-branch exception except..except and universal exception: Exception

    s1 = 'hello'
    try:
        int(s1)
    except IndexError as e:
        print(e)
    except KeyError as e:
        print(e)
    except ValueError as e:
        print(e)
    except Exception as e:
        print(e)

    3. try/except...else

    There is another try/except statement The optional else clause, if used, must be placed after all except clauses.

    The else clause will be executed when no exception occurs in the try clause.

    for arg in sys.argv[1:]:
        try:
            f = open(arg, 'r')
        except IOError:
            print('cannot open', arg)
        else:
            print(arg, 'has', len(f.readlines()), 'lines')
            f.close()

    4. The final execution of exceptions finally

    try-finally statement will execute the final code regardless of whether an exception occurs.

    Define cleanup behavior:

    s1 = 'hello'
    try:
        int(s1)
    except IndexError as e:
        print(e)
    except KeyError as e:
        print(e)
    except ValueError as e:
        print(e)
    #except Exception as e:
    #    print(e)
    else:
        print('try内代码块没有异常则执行我')
    finally:
        print('无论异常与否,都会执行该模块,通常是进行清理工作')

    #invalid literal for int() with base 10: 'hello'

    #This module will be executed regardless of exception or not, usually Carry out cleanup work

    4. Throw an exception raise

    Python uses the raise statement to throw a specified exception. The syntax format of

    raise is as follows:

    raise [Exception [, args [, traceback]]]
    try:
        raise TypeError('抛出异常,类型错误')
    except Exception as e:
        print(e)

    raise The only parameter specifies the exception to be thrown. It must be an exception instance or an exception class (that is, a subclass of Exception).

    If you just want to know if this threw an exception and don't want to handle it, then a simple raise statement can throw it again.

    try:
            raise NameError('HiThere')
        except NameError:
            print('An exception flew by!')
            raise
       
    #An exception flew by!
    #Traceback (most recent call last):
    #  File "", line 2, in ?
    #NameError: HiThere

    5. Custom exceptions

    You can have your own exceptions by creating a new exception class. The exception class inherits from the Exception class, either directly or indirectly, for example:

    In this example, the default __init__() of the Exception class is overridden.

    class EgonException(Exception):
        def __init__(self, msg):
            self.msg = msg
    
        def __str__(self):
            return self.msg
    
    
    try:
        raise EgonException('抛出异常,类型错误')
    except EgonException as e:
        print(e) 
    
    #抛出异常,类型错误

    Basic Exception Class

    When creating a module that may throw many different exceptions, a common approach is to create a basic exception class for this package, and then based on this foundation The class creates different subclasses for different error conditions:

    Most exception names end with "Error", just like standard exception naming.

    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, next, message):
            self.previous = previous
            self.next = next
            self.message = message

    6. Assert

    assert (assert) is used to judge an expression and trigger an exception when the expression condition is false.

    Assertions can directly return an error when the conditions are not met for the program to run, without having to wait for the program to crash after running.

    The syntax format is as follows:

    assert expression

    is equivalent to:

    if not expression:
        raise AssertionError

    assert can also be followed by parameters:

    assert expression [, arguments]

    is equivalent to:

    if not expression:
        raise AssertionError(arguments)

    The following example determines whether the current system is Linux. If the conditions are not met, an exception will be triggered directly without executing the next code:

    import sys
    assert ('linux' in sys.platform), "该代码只能在 Linux 下执行"
    # 接下来要执行的代码
    
    # Traceback (most recent call last):
    #    File "C:/PycharmProjects/untitled/run.py", line 2, in 
    #      assert ('linux' in sys.platform), "该代码只能在 Linux 下执行"
    #  AssertionError: 该代码只能在 Linux 下执行

    The above is the detailed content of Analysis of exception handling examples in Python. For more information, please follow other related articles on the PHP Chinese website!

    Statement
    This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
    详细讲解Python之Seaborn(数据可视化)详细讲解Python之Seaborn(数据可视化)Apr 21, 2022 pm 06:08 PM

    本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于Seaborn的相关问题,包括了数据可视化处理的散点图、折线图、条形图等等内容,下面一起来看一下,希望对大家有帮助。

    详细了解Python进程池与进程锁详细了解Python进程池与进程锁May 10, 2022 pm 06:11 PM

    本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于进程池与进程锁的相关问题,包括进程池的创建模块,进程池函数等等内容,下面一起来看一下,希望对大家有帮助。

    Python自动化实践之筛选简历Python自动化实践之筛选简历Jun 07, 2022 pm 06:59 PM

    本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于简历筛选的相关问题,包括了定义 ReadDoc 类用以读取 word 文件以及定义 search_word 函数用以筛选的相关内容,下面一起来看一下,希望对大家有帮助。

    归纳总结Python标准库归纳总结Python标准库May 03, 2022 am 09:00 AM

    本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于标准库总结的相关问题,下面一起来看一下,希望对大家有帮助。

    分享10款高效的VSCode插件,总有一款能够惊艳到你!!分享10款高效的VSCode插件,总有一款能够惊艳到你!!Mar 09, 2021 am 10:15 AM

    VS Code的确是一款非常热门、有强大用户基础的一款开发工具。本文给大家介绍一下10款高效、好用的插件,能够让原本单薄的VS Code如虎添翼,开发效率顿时提升到一个新的阶段。

    Python数据类型详解之字符串、数字Python数据类型详解之字符串、数字Apr 27, 2022 pm 07:27 PM

    本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于数据类型之字符串、数字的相关问题,下面一起来看一下,希望对大家有帮助。

    python中文是什么意思python中文是什么意思Jun 24, 2019 pm 02:22 PM

    pythn的中文意思是巨蟒、蟒蛇。1989年圣诞节期间,Guido van Rossum在家闲的没事干,为了跟朋友庆祝圣诞节,决定发明一种全新的脚本语言。他很喜欢一个肥皂剧叫Monty Python,所以便把这门语言叫做python。

    详细介绍python的numpy模块详细介绍python的numpy模块May 19, 2022 am 11:43 AM

    本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于numpy模块的相关问题,Numpy是Numerical Python extensions的缩写,字面意思是Python数值计算扩展,下面一起来看一下,希望对大家有帮助。

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Article

    R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
    2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    Repo: How To Revive Teammates
    4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    Hello Kitty Island Adventure: How To Get Giant Seeds
    4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    mPDF

    mPDF

    mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

    SublimeText3 English version

    SublimeText3 English version

    Recommended: Win version, supports code prompts!

    Dreamweaver Mac version

    Dreamweaver Mac version

    Visual web development tools

    Atom editor mac version download

    Atom editor mac version download

    The most popular open source editor

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment