python学习-处理error

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

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值