在 Python 中重新抛出异常

Python 为我们提供了 try-except 块来处理程序中的异常。 它还为我们提供了 raise 语句来手动抛出异常。

本文将讨论如何在 Python 程序中重新抛出异常。


在 Python 中抛出异常

我们可以使用 raise 语句在程序中抛出异常。 raise 语句的语法如下。

raise exception_name

此处,raise 语句将名为 exception_name 的异常作为输入并抛出 Python 解释器处理的异常。

例如,我们可以使用 raise 语句在我们的程序中引发 ValueError 异常。

  1. 以下程序要求用户使用 input() 函数提供一个数字作为输入。 input() 函数将输入作为分配给变量 number 的字符串返回。
  2. 之后,程序检查输入是否仅包含数字(或不包含)。 为此,我们使用 isdigit() 方法。

    isdigit() 方法在对字符串调用时检查字符串的所有字符是否都是十进制数字。 如果是,则返回 True; 否则,它返回 False。

number = input("Please Enter a number:")
if number.isdigit():
    number = int(number)
    square = number * number
    print("The square of {} is {}".format(number, square))
else:
    raise ValueError

输出:

Please Enter a number:Aditya
Traceback (most recent call last):
  File "/home/aditya1117/PycharmProjects/pythonProject/webscraping.py", line 7, in <module>
    raise ValueError
ValueError

在上面的程序中,如果用户提供的输入仅包含十进制数字,则执行 if 块中的代码。 因此,使用 int() 函数将输入转换为整数。

最后,计算并打印整数的平方。

如果用户输入的是十进制数字以外的字符,则执行else语句中的代码,程序抛出ValueError异常。

这里,ValueError 异常是一个内置异常。


在 Python 中使用自定义消息抛出异常

我们还可以使用自定义消息抛出自定义异常。 为此,我们将使用 Exception() 构造函数创建一个异常对象。

Exception() 构造函数将消息字符串作为其输入参数,并在执行后返回异常。 我们可以使用 raise 语句抛出自定义异常,如下例所示。

number = input("Please Enter a number:")
if number.isdigit():
    number = int(number)
    square = number * number
    print("The square of {} is {}".format(number, square))
else:
    raise Exception("The input contains characters other than decimal digits.")

输出:

Please Enter a number:Aditya
Traceback (most recent call last):
  File "/home/aditya1117/PycharmProjects/pythonProject/webscraping.py", line 7, in <module>
    raise Exception("The input contains characters other than decimal digits.")
Exception: The input contains characters other than decimal digits.

在这里,您可以看到程序引发了一个自定义异常,并显示消息输入包含十进制数字以外的字符。


在 Python 中重新抛出异常

Python 中的异常是使用 try-except 块处理的。 当在 try 块中抛出异常时,它会在 except 块中被捕获,并采取适当的措施。

您可以在下面的示例中观察到这一点。

number = input("Please Enter a number:")
try:
    if number.isdigit():
        number = int(number)
        square = number * number
        print("The square of {} is {}".format(number, square))
    else:
        raise Exception("The input contains characters other than decimal digits.")
except Exception:
    print("In the except block. exception handled.")

输出:

Please Enter a number:Aditya
In the except block. exception handled.

在这里,在 try 块中引发了异常。 然后,我们在 except 块中捕获异常,在需要时处理它,并打印一条适当的消息。

如果要在 Python 程序中重新抛出异常,可以在 except 块中使用 raise 语句,如下所示。

number = input("Please Enter a number:")
try:
    if number.isdigit():
        number = int(number)
        square = number * number
        print("The square of {} is {}".format(number, square))
    else:
        raise Exception("The input contains characters other than decimal digits.")
except Exception:
    print("In the except block. exception handled. Rethrowing exception.")
    raise

输出:

Please Enter a number:Aditya
In the except block. exception handled. Rethrowing exception.
Traceback (most recent call last):
  File "/home/aditya1117/PycharmProjects/pythonProject/webscraping.py", line 8, in <module>
    raise Exception("The input contains characters other than decimal digits.")
Exception: The input contains characters other than decimal digits.

在这个例子中,我们首先捕获并处理了 except 块中的异常。 之后我们在Python中使用 raise 语句重新抛出异常。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

迹忆客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值