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
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值