透過拋出錯誤來進行錯誤處理
另一種拋出錯誤的方法是使用 raise。在本練習中,你要在先前定義的 shout_echo() 函式中加入 raise 陳述,當使用者提供給引數 echo 的值小於 0 時,拋出錯誤訊息。
這裡對 shout_echo() 的呼叫使用的是有效的引數值。若要測試並觀察 raise 的作用,只要把 echo 引數改成「負數」即可。別忘了之後把它改回有效值,才能進入下一個練習!
本練習屬於課程
Python 函式入門
練習說明
- 完成
if陳述式,檢查echo的值是否「小於」0。 - 在
if陳述式的主體中加入raise陳述,當使用者提供給echo的值小於 0 時,拋出含有訊息 'echo must be greater than or equal to 0' 的ValueError。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# 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 ____:
____ ____(____)
# 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)