Summary of python exceptions

Python exceptions are errors that occur during program execution and may cause the program to terminate.

In Python, exception handling is a mechanism that allows developers to catch, handle, and report exceptions when they occur in the program, so that the program can continue to run or exit gracefully when an exception occurs.

In Python, exceptions can be standard exceptions (such as SyntaxError and TypeError) or custom exceptions. Standard exceptions are defined internally by Python, while custom exceptions are defined by developers, usually for specific applications or libraries.

Here are some common Python exceptions:

  1. SyntaxError: Syntax error, usually due to syntax errors, such as missing parentheses, colons, etc.
  2. TypeError: Type error, usually caused by combining objects of different types, such as adding a string and a number.
  3. ValueError: Value error, usually caused by a supplied value not in the expected range or format, such as an invalid string supplied when converting a string to an integer.
  4. IndexError: An index error, usually caused by trying to access a non-existing element in a list or tuple.
  5. KeyError: Key error, usually caused by trying to access a key that does not exist in the dictionary.
  6. IOError: Input/Output Error, usually caused by a problem trying to read or write to a file.
  7. AttributeError: Attribute error, usually caused by trying to access an attribute or method that does not exist on the object.

In Python, you can use the try-except statement to catch exceptions and handle them. The try statement contains code that may cause an exception, while the except statement defines the code to be executed when an exception is caught.

Multiple except statements can be used to capture different types of exceptions. try-except can also be combined with else. It means that when the try statement does not detect any exceptions, the content of the else statement will be executed. In addition, you can also use The finally statement defines code that is always to be executed after the try block.

For example:

Case 1: Use try-except statement to catch exceptions and handle them

Example:

try:
100/0 # code that may cause an exception

except ZeroDivisionError: #(捕获特定的异常类型ZeroDivisionError,ZeroDivisionError是Python中的内置异常类之一,用于表示在除数为零的情况下进行了除法操作所引发的异常。)

    print('因为这里打印出异常类型:除数不能为0。')# 处理值错误的代码

Case 2: Use the try-except statement with the else statement (when the try statement does not detect any exception, execute the content of the else statement)

When the try statement detects any exception, the content of the else statement is not executed

>>> try:
...     1 / 0
... except:
...     print("逮到了~")
... else:
...     print("没逮到~")
...

caught~

If an exception is detected in the try statement, then the exception handling content of the except statement is executed:

>>> try:
...     1 / 1
... except:
...     print("逮到了~")
... else:
...     print("没逮到~")
...
1.0

didn't catch~

Case 3: Use a try-except statement with a finally statement (a statement that must be executed regardless of whether an exception occurs or not)

Example:
try:
'abc'+ 123

except TypeError: #TypeError为类型错误,通常是由于将不同类型的对象组合在一起而引起的,如将字符串和数字相加。
    print('因为这里打印出异常类型:类型错误。')# 处理类型错误的代码
finally:
    print('不论是否无法异常,都执行这句话') # 无论是否发生异常都会执行的代码

Exception handling is one of the important concepts in Python. Developers should know how to catch and handle exceptions correctly to ensure the stability and reliability of the program.

Advanced: Ways to catch exceptions

Two methods of catching exceptions: No matter what kind of exception, the exception information is captured.

1. Use Exception: All exceptions are subclasses of Exception. So Exception can match all types of exceptions.
Example:

>>> try:
    100/0
except Exception  as e:
    print('未知异常:', e)
# 对于很多刚学Python或者是学着学着迷茫了的小伙伴,我给大家准备了一套Python的学习资料。
# 包括数百本电子书、Python基础视频教程、项目实战,疑难解答,直接在文末名片自取。
   
未知异常: division by zero
>>>

The cause of the exception can be captured normally, but the detailed exception information (the location where the exception was sent and the code of the exception) cannot be output.

2. Use the traceback module: Use the format_exc function in the traceback module to display the exception information and the function call stack where the exception occurred.

Example:

>>>  import traceback
>>>  try:
    100/0
except  :
    print(traceback.format_exc())
 
 
Traceback (most recent call  last):
  File "<pyshell#5>", line 2, in <module>
ZeroDivisionError: division by  zero
>>>

The above code will print out the detailed function call stack information that caused the exception

Guess you like

Origin blog.csdn.net/ooowwq/article/details/130388794