python - 错误处理和异常

异常的几种常见形式
在Python中,try是用于处理异常的关键字。它与except一起使用,用于捕获可能发生的异常并执行相应的处理代码。

try语句块中包含可能引发异常的代码。如果在try块中发生异常,程序将立即跳转到except块,并执行指定的异常处理代码。如果在try 块中没有发生异常,则跳过except块,继续执行后续的代码。

以下是try-except语句的基本语法:

try:
# 可能引发异常的代码
except ExceptionType:
# 异常处理代码

在except语句中,ExceptionType是指定要捕获的异常类型。如果未指定异常类型,则将捕获所有异常。可以指定多个不同的异常类型来 处理不同类型的异常。还可以使用except语句块来处理多个异常。

通过使用try-except语句,可以优雅地处理Python程序中可能发生的异常情况,避免程序崩溃并提供友好的错误处理。

  1. Handling a specific exception:
try:
    x = 10 / 0    #如果代码需要除法,要把除以0 这种情况去除
except ZeroDivisionError:   #捕获到 0, 即错误 ZeroDivisionError,
    print("Division by zero is not allowed")  #告诉用户你不能这么干
  1. Handling multiple exceptions:
try:   #捕获多种错误的写法
    x = int(input("Enter a number: "))
    result = 10 / x
except ValueError:  
    print("Invalid input. Please enter a number.")
except ZeroDivisionError:
    print("Division by zero is not allowed")
  1. Using else block to execute code when no exceptions are raised:
try:  #使用else运行最终想要实现的功能
    x = int(input("Enter a number: "))
    result = 10 / x
except ValueError:
    print("Invalid input. Please enter a number.")
except ZeroDivisionError:
    print("Division by zero is not allowed")
else:
    print("Result:", result)
  1. Using finally block to execute code regardless of whether an exception is raised:
try:   #finally实现,无论是否有错误都会运行的语句
    file = open("example.txt", "r")
    data = file.read()
except FileNotFoundError:
    print("File not found")
finally:
    file.close()
[root@learning ~]# cat try.py   #情况1 例子
try:
    x = 10 / 0
except ZeroDivisionError:
    print("Division by zero is not allowed")
[root@learning ~]# python3.11 try.py
Division by zero is not allowed 

[root@learning ~]# cat try1.py   #情况2 例子
try:
    x = int(input("Enter a number: "))
    result = 10 / x
except ValueError:
    print("Invalid input. Please enter a number.")
except ZeroDivisionError:
    print("Division by zero is not allowed")
[root@learning ~]# python3.11 try1.py
Enter a number: 0
Division by zero is not allowed
[root@learning ~]# python3.11 try1.py
Enter a number: a
Invalid input. Please enter a number. 

[root@learning ~]# cat try3.py   #情况3
try:
    x = int(input("Enter a number: "))
    result = 10 / x
except ValueError:
    print("Invalid input. Please enter a number.")
except ZeroDivisionError:
    print("Division by zero is not allowed")
else:
    print("Result:", result)
[root@learning ~]# python3.11 try3.py
Enter a number: 0
Division by zero is not allowed
[root@learning ~]# python3.11 try3.py
Enter a number: a
Invalid input. Please enter a number.
[root@learning ~]# python3.11 try3.py
Enter a number: 9
Result: 1.1111111111111112 

[root@learning ~]# cat try4.py   #情况4
try:
    file = open("example.txt", "r")
    data = file.read()
except FileNotFoundError:
    print("File not found")
finally:
    file.close()
[root@learning ~]# python3.11 try4.py  #文件存在时的运行结果
[root@learning ~]# rm example.txt
rm: remove regular file ‘example.txt’? y
[root@learning ~]# python3.11 try4.py   #文件不存在时的运行结果
File not found 
Traceback (most recent call last):
  File "/root/try4.py", line 7, in <module>
    file.close()
    ^^^^
NameError: name 'file' is not defined. Did you mean: 'filter'?

[root@learning ~]# cat selfex2.py   #自定义异常
class ZeroDivisionError(Exception):
    def __init__(self, message="Cannot divide by zero"):
        self.message = message
        super().__init__(self.message) 

def divide_ten_by_x(x):  #定义函数
    if x == 0:
        raise ZeroDivisionError
    result = 10 / x
    return result 

try:
    x = int(input("Enter a number: "))
    result = divide_ten_by_x(x)
    print(f"10 divided by {x} is {result}")
except ZeroDivisionError as e:  #常用写法,e是变量,将异常对象存储在e 中
    print(e)
[root@learning ~]# python3.11 selfex2.py  #运行结果
Enter a number: 0
Cannot divide by zero
[root@learning ~]# python3.11 selfex2.py
Enter a number: a
Invalid input. Please enter a number.
[root@learning ~]# python3.11 selfex2.py
Enter a number: 9
10 divided by 9 is 1.1111111111111112

你可能感兴趣的:(python,开发语言)