https://blog.csdn.net/qq_35831906/category_12375510.html?spm=1001.2014.3001.5482
Table of contents
A common python exception type and solution
Two common exception handling statements
2 try...except...else statement
3 try...except...finally statement
4 Use the raise statement to throw an exception
Column guide
This article is included in the column "Proficient in Python in 100 Days" . This column is aimed at beginners and advanced users. The system quickly grasps the core concepts and practical skills of the Python programming language, and masters the basic syntax, data types, functions, modules, and object-oriented programming of Python. Wait for key knowledge , and then go deep into actual project combat, and use python to solve practical problems!
Explore the charm of Python and master the programming world! Let's GO!
Column subscription address: https://blog.csdn.net/qq_35831906/category_12375510.html
In Python, an exception is an error or unexpected condition that occurs while the program is running and prevents the program from continuing normally. Python provides a set of built-in exception classes for representing different types of errors. When exceptions occur in the program, these exceptions can be caught and processed through the exception handling mechanism, so as to gracefully handle the error situation.
A common python exception type and solution
In Python, there are many built-in exception types used to represent different errors or exceptional conditions.
Exception is the base class of all built-in exceptions, and all exception classes in Python inherit from the Exception class. When an exception occurs in the program, the corresponding exception object will be thrown. If these exceptions are not handled, the program will terminate execution.
Common exception types and solutions in python:
1.SyntaxError
: Syntax errors, usually caused by writing errors in the code, such as typos, missing colons, etc.Solution: Check the code carefully to make sure the syntax is correct.
2.IndentationError
: Indentation errors, usually caused by incorrectly indented code.Solution: Check whether the indentation of the code is correct. It is recommended to use 4 spaces as the indentation.
3.NameError
: Bad name, usually caused by using an undefined variable or function name.Workaround: Make sure variable and function names are defined correctly or before use.
4.TypeError
: Type error, usually caused by using the wrong data type.Solution: Confirm whether the data types match. If not, try to perform type conversion or use the correct data type.
5.ValueError
: Value error, usually caused by using an illegal value.Solution: Confirm whether the value range of the data is correct, and ensure that legal values are used.
6.ZeroDivisionError
: Divide by zero error, usually caused by a division by zero in a division operation.Solution: Make sure that the divisor is not zero, and you can perform exception handling when the divisor is zero to avoid program crashes.
7.IndexError
: Index error, usually caused by using an index that exceeds the range of the sequence.Solution: Confirm whether the index value is within the range of the sequence, and ensure that it does not exceed the length of the sequence.
8.KeyError
: Key error, usually caused by using a key that does not exist.Workaround: Make sure the key exists in the dictionary, you can use
in
the keyword to check if a key exists.
9.FileNotFoundError
: File does not exist error, usually caused by trying to open a file that does not exist.Solution: Check whether the file path is correct and make sure the file exists.
10.ImportError
: Import error, usually caused by a problem importing a module or package.Solution: Confirm whether the path of the module or package is correct, and ensure that the module exists.
11. IOError (input and output error): This exception is thrown when a problem related to file input and output occurs.
Solution: Make sure the file access permissions are correct and check for other issues related to file input and output
12.AttributeError (Attribute Error): This exception is thrown when using an attribute or method that does not exist.
Solution: Make sure that the property or method exists on the object, or that the object is properly initialized before accessing the property or calling the method.
RuntimeError
: runtime error, which is usually thrown as a base class because it cannot be classified into another exception type.
The general way to handle exceptions is to use
try...except
statements. Execute the code that may throw an exception intry
the block, and if an exception occurs, it will jump toexcept
the block to handle the exception. By catching and handling exceptions, program crashes can be avoided, and the robustness and fault tolerance of the program can be increased.
Two common exception handling statements
Exception is the base class of all built-in exceptions, and all exception classes in Python inherit from the Exception class. When an exception occurs in the program, the corresponding exception object will be thrown. If these exceptions are not handled, the program will terminate execution. In order to resolve the exception, we can take the following approach:
1 try...except statement
Use a try...except statement in a block of code that might throw an exception to catch and handle the exception. Put code that might throw an exception in a try block, and if an exception occurs, handle the exception in an except block.
Example 1: Catch specific exception types
try:
num1 = int(input("请输入一个整数: "))
num2 = int(input("请输入另一个整数: "))
result = num1 / num2
print("结果:", result)
except ValueError:
print("请输入有效的整数值!")
except ZeroDivisionError:
print("除数不能为零!")
In the above example, we are trying to convert the string entered by the user to an integer and do the division. If the user enters something that is not a valid integer, ValueError
an exception is raised and an appropriate error message is printed. If the divisor is zero, ZeroDivisionError
an exception is raised and an appropriate error message is printed.
Example 2: Catch all exceptions
try:
num = int(input("请输入一个整数: "))
result = 10 / num
print("结果:", result)
except Exception as e:
print("发生了异常:", e)
In this example, we try to convert the string entered by the user into an integer and use it as the divisor for division. No matter what type of exception occurs, except Exception
the statement will catch and handle the exception, and assign the exception object to the variable e
. Then, we print out the exception message.
Example 3: Catch multiple exception types
try:
file = open("nonexistent.txt", "r")
content = file.read()
file.close()
print("文件内容:", content)
except FileNotFoundError:
print("文件不存在!")
except PermissionError:
print("没有文件访问权限!")
except Exception as e:
print("发生了异常:", e)
In the above example, we are trying to open a non-existing file and read its contents. An exception is raised if the file does not exist FileNotFoundError
; an exception is raised if there are insufficient permissions to access the file PermissionError
. We use multiple except
statements to catch different types of exceptions and print out corresponding error messages. If any other type of exception occurs, it will be except Exception
caught by the statement, and the exception message will be printed.
2 try...except...else statement
In addition to catching exceptions, you can also add an else block in the try...except statement to handle the situation when there is no exception.
It allows us to try to execute a block of code that might throw an exception, and if an exception occurs, the except
exception case can be handled in the block, while else
the normal execution case is handled in the block.
The grammatical structure is as follows:
try:
# 可能引发异常的代码块
except ExceptionType:
# 处理指定类型的异常
else:
# 没有异常时执行的代码块
Example 1:
def divide(x, y):
try:
result = x / y
except ZeroDivisionError:
print("Error: Division by zero!")
else:
print(f"The result of {x} divided by {y} is {result}")
divide(10, 2) # Output: The result of 10 divided by 2 is 5.0
divide(10, 0) # Output: Error: Division by zero!
Example 2;
try:
num1 = int(input("请输入一个整数: "))
num2 = int(input("请输入另一个整数: "))
result = num1 / num2
except ValueError:
print("请输入有效的整数值!")
except ZeroDivisionError:
print("除数不能为零!")
else:
print("结果:", result)
In this example, we divide two integers entered by the user. If the user input is not a valid integer,
ValueError
an exception will be thrown; if the divisor is zero,ZeroDivisionError
an exception will be thrown. If no exception occurs,else
the result will be printed out in the block.Regardless of whether it is
except
a block orelse
a block, at most one block will be executed. If an exception occurs, the correspondingexcept
block will be executed; if no exception occurs,else
the block will be executed.Another: The except block in the try-except-else statement is optional, you can choose to use only the try and else blocks, or add multiple except blocks to catch different types of exceptions
3 try...except...finally statement
The finally block can be added in the try...except statement, and the code in the finally block will be executed regardless of whether an exception occurs. It is used to catch and handle exceptions that may occur, and to execute some code block regardless of whether an exception occurs or not.
try
A block contains code that may throw an exception,except
a block is used to handle an exception, andfinally
the code inside the block is always executed whether or not an exception occurs.
The following are try...except...finally
detailed explanations and examples of the statements:
try
Block: Contains code that may throw an exception.
except
Blocks: Used to catch and handle exceptions. Whentry
an exception occurs within a block, the program skipstry
the remaining code of the block and executesexcept
the code within the block. You can use itexcept
followed by a specific exception type to handle a specific type of exception, or you can useexcept
it without any exception type to handle all exceptions.
finally
Block: The contained code is always executed regardless of whether an exception occurs. Regardless of whether an exception occurs,finally
the code in the block will be executed to ensure that some necessary cleanup work is performed when an exception occurs.
Here is a simple example demonstrating try...except...finally
the use of the statement:
def divide(x, y):
try:
result = x / y
except ZeroDivisionError:
print("除数不能为零!")
result = None
finally:
print("执行finally块!")
return result
# 调用函数
print(divide(10, 2)) # 输出: 5.0
print(divide(10, 0)) # 输出: 除数不能为零! 执行finally块! None
In the above example, we defined a
divide
function that takes two argumentsx
andy
tries tox
divide byy
. Ify
zero,ZeroDivisionError
an exception will be triggered. Intry
the block, we try to perform the division operation, and if an exception occurs,except
the code in the block is executed to print the error message.finally
The code in the block will be executed whether or not an exception occurs .Note:
finally
The code in the block is optional and can be omitted and not used. Intry...except
a structure,try
blocks are required, whileexcept
blocks andfinally
blocks are optional.
4 Use the raise statement to throw an exception
In Python, raise
exceptions can be thrown manually using the statement. raise
Statements allow you to actively raise exceptions at specific points in your code, allowing error handling if necessary.
raise
The general syntax of the statement is as follows:
raise [ExceptionType[(args)]]
Among them, ExceptionType
is the type of exception, which can be a built-in exception type (such as ValueError
, TypeError
etc.), or a custom exception type. args
is an optional parameter to provide additional information about the exception.
Here is an raise
example of using a statement to throw an exception:
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)
In the above example, we defined a
divide
function that takes two parametersx
andy
. Ify
zero, we useraise
the statement to throw anValueError
exception with an error message "divisor cannot be zero!".try
Call the function in the block ,divide
andexcept
catch and handle the thrown exception in the block.
Output result:
发生异常: 除数不能为零!
By using
raise
statements, you can proactively raise exceptions where needed and perform exception handling where appropriate. This can enhance the readability and robustness of the code, making error handling more flexible and accurate.
5 custom exception types
If you need to handle a specific type of exception, you can customize the exception class and throw that exception when needed.
class MyError(Exception):
def __init__(self, message):
self.message = message
try:
raise MyError("自定义异常")
except MyError as e:
print("捕获自定义异常:", e.message)
6 exception chain processing
If the exception cannot be handled at the current location, the exception can be passed to the upper layer call function for processing, forming an exception chain.
def func():
try:
result = 10 / 0
except ZeroDivisionError as e:
raise MyError("发生异常:") from e
try:
func()
except MyError as e:
print("捕获异常链:", e)
These methods above can help us handle and resolve exceptions and ensure the stability and reliability of the program. However, it should be noted that exception handling should be used reasonably, avoid excessive use of try...except statements, and exception handling should be performed according to the specific situation to keep the code clear and readable.
Python program exceptions and debuggingNext: [100 days proficient in python] Day18: Python program exceptions and debugging_Common program debugging methods and skills, how to separate debugging code from official code_LeapMay's Blog-CSDN Blog