我是python的新手,这是我第一次在这里提出问题,因此请让我知道问题中是否缺少某些内容或不清楚。我一直在试图理解引发异常的真正作用。例如,如果以下代码执行为 myScript.py someText (脚本+一个参数作为字符串),由于执行x = float(i1)时 someText 产生ValueError,因此解析了无效的参数。因此,将执行 ValueError 除外。在此块中,引发ValueError。这将终止循环,并执行代码行 print(e)。
引发ValueError是否总是终止循环和代码块?我有点困惑,因为在x = float(i1)中已经产生了ValueError。此ValueError和引发的ValueError有什么区别?
sh "curl ..."
答案 0 :(得分:1)
未捕获的异常总是被“冒泡”,直到被捕获或无法进一步冒泡-在这种情况下,程序将崩溃。
如果您发现并重新举起(或举起其他东西)它会冒出来。
在您的情况下,您会引发相同的Exception,但具有与默认消息不同的“ buisnesslogic”-“更具可读性”消息。
除了为用户提供的“自定义”提示文字外,您还可以抛出自己的异常,该异常执行您想做的特殊事情:
test[sub("^develop", "", test) == test]
打印:
# custom exception with special functionality
class MyApplicationMessage(Exception):
def __init__(self, message):
super().__init__(message)
# calculate something meaningfull f.e. a tranlated error message
self.customTranslatedMessage = self._translator(message)
def _translator(self, ex):
# do something that makes sense, f.e. logging or posting to a online
# error log
return str(ex).upper()[::-1]
def fail_with_custom_exception():
try:
failed = int("hallo")
except ValueError as m:
raise MyApplicationMessage(str(m))
try:
fail_with_custom_exception()
except MyApplicationMessage as e:
print(e.customTranslatedMessage)
这不是重点-您可以做任何事情-f.e.向管理员发送邮件,并让他在阅读邮件后立即修复错误...
答案 1 :(得分:0)
当您从x = float(i1)
获得异常并进入except ValueError:
或except IndexError:
时,您将不再位于try:
块中并在那里引发另一个异常必须向外传播。
在您的代码中,此“ propagate outwards
”首先退出while True:
循环,而程序所在的def read_numb():
退出另一个try:
,您通过打印来处理异常。 (如果不存在,解释器将退出打印Traceback)
相反,except Exception as e:
最好定义自己的异常:
class MyException(Exception):
pass
def read_numb():
# details elided
except ValueError:
raise MyException("Oops! %s was no valid number. " % i1)
except IndexError:
raise MyException("You must give a value!")
try:
read_numb()
except MyException as e:
print(e)
这样,就不会捕获更多与程序员相关的错误,并且您可以更好地跟踪问题。