在 Python 中重新抛出异常
Python 为我们提供了 try-except 块来处理程序中的异常。 它还为我们提供了 raise 语句来手动抛出异常。
本文将讨论如何在 Python 程序中重新抛出异常。
在 Python 中抛出异常
我们可以使用 raise
语句在程序中抛出异常。 raise
语句的语法如下。
raise exception_name
此处,raise
语句将名为 exception_name 的异常作为输入并抛出 Python 解释器处理的异常。
例如,我们可以使用 raise 语句在我们的程序中引发 ValueError 异常。
-
以下程序要求用户使用
input()
函数提供一个数字作为输入。input()
函数将输入作为分配给变量 number 的字符串返回。 -
之后,程序检查输入是否仅包含数字(或不包含)。 为此,我们使用
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
语句重新抛出异常。
相关文章
Pandas DataFrame DataFrame.shift() 函数
发布时间:2024/04/24 浏览次数:133 分类:Python
-
DataFrame.shift() 函数是将 DataFrame 的索引按指定的周期数进行移位。
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
Pandas read_csv()函数
发布时间:2024/04/24 浏览次数:254 分类:Python
-
Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。
Pandas 多列合并
发布时间:2024/04/24 浏览次数:628 分类:Python
-
本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。
Pandas loc vs iloc
发布时间:2024/04/24 浏览次数:837 分类:Python
-
本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串