Python Basics (9): Errors and Exceptions

foreword

In Python, errors and exceptions are problems or error conditions that may arise during the execution of a program. When a program encounters an error or exception, it raises the corresponding error or exception object, thereby interrupting the normal flow of execution of the program. The following are detailed definitions and descriptions of errors and exceptions, along with examples:

1. Error

A bug is an unhandled or repairable problem that occurs during program execution, usually due to programming errors or system problems. Errors are divided into syntax errors (SyntaxError) and logic errors (LogicError).

1.1 Syntax errors

# 语法错误示例,缺少冒号:
if x > 5
    print("x 大于 5")

1.2 Logic errors

# 逻辑错误示例,条件判断错误
x = 10
if x < 5:
    print("x 小于 5")

2. Exception

Exceptions occur during program execution 可预测的问题或异常情况and can be caught and handled through exception handling mechanisms. Python provides many built-in exception classes, and you can also customize exception classes.

In Python, the exception handling mechanism allows us to catch and handle exceptions in the program, so that we can perform specific operations when encountering problems without interrupting the normal execution flow of the program. Exception handling works as follows:

2.1 Exception capture (Try-Except)

Use tryand exceptblock to catch and handle exceptions. Place code that may throw an exception in trya block, and if an exception occurs, the remaining tryblock code is skipped and control flow is passed to the matching exceptblock.

Example:

try:
    num1 = int(input("请输入一个整数: "))
    num2 = int(input("请输入另一个整数: "))
    result = num1 / num2
    print("结果:", result)
except ValueError:
    print("输入的不是有效的整数")
except ZeroDivisionError:
    print("除数不能为零")

2.2 Exception throwing (Raise)

When an error or exceptional condition occurs during code execution, raisean exception can be manually raised using the statement. Exception objects can be built-in exception classes or custom exception classes.

Example:

def divide(x, y):
    if y == 0:
        raise ValueError("除数不能为零")
    return x / y

try:
    result = divide(10, 0)
    print("结果:", result)
except ValueError as e:
    print(e)

2.3 try-except-else statement

try-except-elsestatement allows tryan additional block of code, elsethe block, to be executed when the code within the block does not throw any exceptions.

Example:

try:
    # 尝试执行可能引发异常的代码
    num1 = int(input("请输入一个整数: "))
    num2 = int(input("请输入另一个整数: "))
    result = num1 / num2
except ValueError:
    # 处理值错误异常
    print("输入的不是有效的整数")
except ZeroDivisionError:
    # 处理零除错误异常
    print("除数不能为零")
else:
    # 没有异常发生时执行的代码
    print("结果:", result)

2.4 try-except-finally statement

try-except-finallyA statement allows a block of trycode, a block, to be executed both when the code in the block throws an exception or when it does not throw an exception .必须执行finally

Example:

try:
    # 尝试执行可能引发异常的代码
    file = open("myfile.txt", "r")
    content = file.read()
except FileNotFoundError:
    # 处理文件不存在异常
    print("文件不存在")
except Exception as e:
    # 处理其他异常
    print("发生了异常:", e)
finally:
    # 无论是否引发异常,都会执行的代码
    file.close()

2.5 try-except-else-finally statement

try-except-else-finallyThe statement combines the functionality of the previous two statements, allowing tryan additional block of code to be executed if the code in the block throws an exception or not, and a block of code that must be executed at the end

Example:

try:
    # 尝试执行可能引发异常的代码
    num1 = int(input("请输入一个整数: "))
    num2 = int(input("请输入另一个整数: "))
    result = num1 / num2
except ValueError:
    # 处理值错误异常
    print("输入的不是有效的整数")
except ZeroDivisionError:
    # 处理零除错误异常
    print("除数不能为零")
else:
    # 没有异常发生时执行的代码
    print("结果:", result)
finally:
    # 无论是否引发异常,都会执行的代码
    print("执行finally块")

try-exceptDifferent usages of these statements can be selected according to actual needs. They provide more flexibility and control, allowing us to perform specific actions when handling exceptions, ensuring the integrity of the program 可靠性和稳定性.

2.6 Execution process of exception handling

  • First, the try clause (the part between the try and except keywords) is executed,
  • If no exception occurs, the except clause is ignored after the try statement is executed
  • When an exception occurs, the normal flow of program execution continues 立即中断, the rest of the clause is ignored, and a jump is made to exceptthe block matching the exception type.
  • If no matching exceptblock is found, the exception is propagated to the upper code that called the current code until a matching exceptblock is found or the top level of the program is reached.
  • If the exception is not caught up the entire call stack, the program will terminate with the default exception message.

3. Custom exceptions

In Python, you can customize exception classes to represent specific errors or unusual conditions, so that these exceptions can be thrown and caught in the program. Custom exception classes need to inherit from built-in Exceptionclasses or their subclasses, and can add custom properties and methods.

The following are descriptions and examples of custom exceptions:

3.1 Definition of custom exception class

Custom exception classes can Exceptionbe defined by inheriting classes or their subclasses. Additional properties and methods can be added to custom exception classes to better describe and handle specific exception conditions.

Example:

class MyException(Exception):
    pass

3.2 Throw a custom exception

Use raisestatements to throw custom exceptions in your program. After a custom exception is thrown, the program will interrupt the normal execution flow and transfer control to the corresponding exception handling code.

Example:

def divide(x, y):
    if y == 0:
        raise MyException("除数不能为零")
    return x / y

try:
    result = divide(10, 0)
    print("结果:", result)
except MyException as e:
    print(e)

3.3 Attributes and methods of custom exceptions

Custom exception classes can add properties and methods to provide additional information about the exception or perform specific operations.

Example:

class MyException(Exception):
    def __init__(self, message, code):
        super().__init__(message)
        self.code = code

    def get_error_code(self):
        return self.code

try:
    raise MyException("自定义异常", 500)
except MyException as e:
    print(e)
    print("错误代码:", e.get_error_code())

4. Built-in exception class

4.1 Hierarchy of exception classes

Exception classes in Python form a hierarchy, and these exception classes are built-in to represent different types of errors and exceptional conditions. The following is a schematic diagram of the hierarchy of Python exception classes:

BaseException
├── SystemExit
├── KeyboardInterrupt
├── GeneratorExit
├── Exception
    ├── StopIteration
    ├── StopAsyncIteration
    ├── ArithmeticError
    │   ├── FloatingPointError
    │   ├── OverflowError
    │   └── ZeroDivisionError
    ├── AssertionError
    ├── AttributeError
    ├── BufferError
    ├── EOFError
    ├── ImportError
        ├── ModuleNotFoundError
    ├── LookupError
    │   ├── IndexError
    │   └── KeyError
    ├── MemoryError
    ├── NameError
        ├── UnboundLocalError
    ├── OSError
        ├── FileNotFoundError
        ├── PermissionError
    ├── ReferenceError
    ├── RuntimeError
        ├── NotImplementedError
        ├── RecursionError
    ├── SyntaxError
        ├── IndentationError
            ├── TabError
    ├── SystemError
    ├── TypeError
    ├── ValueError
        ├── UnicodeError
            ├── UnicodeDecodeError
            ├── UnicodeEncodeError
            └── UnicodeTranslateError
    ├── Warning
        ├── DeprecationWarning
        ├── PendingDeprecationWarning
        ├── RuntimeWarning
        ├── SyntaxWarning
        ├── UserWarning
        ├── FutureWarning
        ├── ImportWarning
        ├── UnicodeWarning
        └── BytesWarning

In this hierarchy, BaseExceptionis the base class of all exception classes, Exceptionbut the base class of most built-in exception classes. Exception classes are classified and hierarchically divided according to their characteristics and relationships, so that they can be handled according to different exception types.

4.2 Common built-in exception classes and descriptions

Here are some common Python built-in exception classes and their descriptions:

exception class illustrate
Exception Base class for all exception classes
SyntaxError Grammatical errors
IndentationError indentation error
TypeError type error
NameError wrong name
ValueError wrong value
ZeroDivisionError division by zero error
FileNotFoundError file does not exist error
IOError input/output error
IndexError index error
KeyError key error
AttributeError attribute error
ImportError import error
ModuleNotFoundError module does not exist error
StopIteration iterator has no more values ​​to return error
KeyboardInterrupt User Interrupt Execution
AssertionError assertion failed error
TypeError parameter type error
UnboundLocalError Access to uninitialized local variable error
OverflowError overflow error
MemoryError out of memory error
RuntimeError runtime error
FileExistsError file already exists error
PermissionError permission error

These are some of the common Python built-in exception classes, each representing a specific type of error or exceptional condition. When writing code, understanding these exception classes can help us better understand and deal with problems that may arise in the program.

Guess you like

Origin blog.csdn.net/qq_29864051/article/details/131354326