我可以在同一个函数中引发和处理异常吗
Can I raise and handle exceptions in the same function
我正在引发异常并尝试在代码段中处理异常。引发异常部分和处理异常部分在一个函数中完成。这样做有错吗?
import sys
def water_level(lev):
if(lev<10):
raise Exception("Invalid Level!")
print"New level=" # If exception not raised then print new level
lev=lev+10
print lev
try:
if(level<10):
print"Alarming situation has occurred."
except Exception:
sys.stdout.write('\a')
sys.stdout.flush()
else:
os.system('say "Liquid level ok"')
print"Enter the level of tank"
level=input()
water_level(level) #function call
输出未处理异常。有人可以解释一下为什么吗?
最好只在函数中引发异常,然后在调用该函数时捕获它,这样您的函数就不会做太多事情,并且您的错误处理是独立的。它使您的代码更简单。
您的代码从未到达 except
子句,因为如果水位太低,它会引发异常并跳出函数,如果没问题,它只会到达 else
子句。 try
子句中的 print
语句也从未达到,因为它与引发异常的条件相同,而跳出的条件相同。
你的代码应该是这样的...
import sys
import os
def water_level(level):
#just raise exception in function here
if level < 10:
raise Exception("Invalid Level!")
level = level + 10
print("New level=") # If exception not raised then print new level
print(level)
#function call
print("Enter the level of tank")
#cast to int
level=int(input())
try:
#call function in here
water_level(level)
#catch risen exceptions
except Exception as e:
sys.stdout.write('\a')
sys.stdout.flush()
#print exception(verification)
print(e)
print("Alarming situation has occurred.")
else:
os.system('say "Liquid level ok"')
请注意,我纠正了一些其他缺陷
import os
丢失
- 您应该将
input()
转换为数字,以便进行数字比较和加法
- 尽量避免捕获最不具体的异常
Exception
因为你也会捕获所有其他异常。(这就是我添加 print(e)
的原因)-> 考虑自定义异常
我正在引发异常并尝试在代码段中处理异常。引发异常部分和处理异常部分在一个函数中完成。这样做有错吗?
import sys
def water_level(lev):
if(lev<10):
raise Exception("Invalid Level!")
print"New level=" # If exception not raised then print new level
lev=lev+10
print lev
try:
if(level<10):
print"Alarming situation has occurred."
except Exception:
sys.stdout.write('\a')
sys.stdout.flush()
else:
os.system('say "Liquid level ok"')
print"Enter the level of tank"
level=input()
water_level(level) #function call
输出未处理异常。有人可以解释一下为什么吗?
最好只在函数中引发异常,然后在调用该函数时捕获它,这样您的函数就不会做太多事情,并且您的错误处理是独立的。它使您的代码更简单。
您的代码从未到达 except
子句,因为如果水位太低,它会引发异常并跳出函数,如果没问题,它只会到达 else
子句。 try
子句中的 print
语句也从未达到,因为它与引发异常的条件相同,而跳出的条件相同。
你的代码应该是这样的...
import sys
import os
def water_level(level):
#just raise exception in function here
if level < 10:
raise Exception("Invalid Level!")
level = level + 10
print("New level=") # If exception not raised then print new level
print(level)
#function call
print("Enter the level of tank")
#cast to int
level=int(input())
try:
#call function in here
water_level(level)
#catch risen exceptions
except Exception as e:
sys.stdout.write('\a')
sys.stdout.flush()
#print exception(verification)
print(e)
print("Alarming situation has occurred.")
else:
os.system('say "Liquid level ok"')
请注意,我纠正了一些其他缺陷
import os
丢失- 您应该将
input()
转换为数字,以便进行数字比较和加法 - 尽量避免捕获最不具体的异常
Exception
因为你也会捕获所有其他异常。(这就是我添加print(e)
的原因)-> 考虑自定义异常