Home > Backend Development > Python Tutorial > Analysis of exception handling examples in Python

Analysis of exception handling examples in Python

WBOY
Release: 2023-05-16 14:28:06
forward
1568 people have browsed it
    ##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'
    Copy after login

    3. Exception handling

    1. Basic syntax try...except

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

    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()
    Copy after login

    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)
    Copy after login

    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)
    Copy after login

    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()
    Copy after login

    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('无论异常与否,都会执行该模块,通常是进行清理工作')
    Copy after login

    #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]]]
    Copy after login
    try:
        raise TypeError('抛出异常,类型错误')
    except Exception as e:
        print(e)
    Copy after login

    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
    Copy after login

    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) 
    
    #抛出异常,类型错误
    Copy after login

    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
    Copy after login

    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
    Copy after login

    is equivalent to:

    if not expression:
        raise AssertionError
    Copy after login

    assert can also be followed by parameters:

    assert expression [, arguments]
    Copy after login

    is equivalent to:

    if not expression:
        raise AssertionError(arguments)
    Copy after login

    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 下执行
    Copy after login

    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!

    Related labels:
    source:yisu.com
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template