1.try-except
如果出现错误,使用try-except也可以运行下去,并且可以输出出现问题的原因。
创建一个空字符串:shout_words=""
# Define shout_echo
def shout_echo(word1, echo=1):
"""Concatenate echo copies of word1 and three
exclamation marks at the end of the string."""
# Initialize empty strings: echo_word, shout_words
echo_word=""
shout_words=""
# Add exception handling with try-except
try:
# Concatenate echo copies of word1 using *: echo_word
echo_word = word1*echo
# Concatenate '!!!' to echo_word: shout_words
shout_words = echo_word+"!!!"
except:
# Print error message
print("word1 must be a string and echo must be an integer.")
# Return shout_words
return shout_words
# Call shout_echo
shout_echo("particle", echo="accelerator")
2.Error handling by raising an error
raise ValueError('echo must be greater than or equal to 0')
:如果条件成立(即 echo
的值小于 0),则会引发一个 ValueError
异常,并且异常的消息是 'echo must be greater than or equal to 0'
。这会中断程序的执行,并将异常抛出到上层调用栈中,可以被捕获和处理。
# Define shout_echo
def shout_echo(word1, echo=1):
"""Concatenate echo copies of word1 and three
exclamation marks at the end of the string."""
# Raise an error with raise
if echo<0:
raise ValueError('echo must be greater than or equal to 0')
# Concatenate echo copies of word1 using *: echo_word
echo_word = word1 * echo
# Concatenate '!!!' to echo_word: shout_word
shout_word = echo_word + '!!!'
# Return shout_word
return shout_word
# Call shout_echo
shout_echo("particle", echo=5)
#输出结果
Traceback (most recent call last):
File "script.py", line 72, in exceptionCatcher
raise exception
File "script.py", line 3361, in run_ast_nodes
if (await self.run_code(code, result, async_=asy)):
File "script.py", line 3458, in run_code
self.showtraceback(running_compiled_code=True)
File "script.py", line 2066, in showtraceback
self._showtraceback(etype, value, stb)
File "script.py", line 72, in exceptionCatcher
raise exception
File "script.py", line 3441, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "script.py", line 20, in <module>
shout_echo("particle", echo=-1)
File "script.py", line 8, in shout_echo
raise ValueError('echo must be greater than or equal to 0')
ValueError: echo must be greater than or equal to 0