在函数定义周围使用try-except忽略异常处理 [英] Exception handling is ignored with try-except around a function definition

查看:141
本文介绍了在函数定义周围使用try-except忽略异常处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的消息除以0​​错误"没有通过,而是出现了正常的ZeroDivisionError.

My message "Divide by 0 error" is not going through, instead I'm getting a normal ZeroDivisionError.

#!/usr/bin/python

t = raw_input("do you want to play a game?[y/n]" )

#r = raw_input("Please enter a number")

#e = raw_input("Please enter a number again")

try:
 def di (a, b):
  return  a/b
except ZeroDivisionError:
 print "Divide by 0 Error"

while t == "y":
  u = raw_input("Please enter / sign ")
  if u == "/":
   r = int(raw_input("Please enter a number"))
  try:
   e = int(raw_input("Please enter a number again"))
   print "the answer is", di(r, e)
   t = raw_input("do you want to play a game?[y/n]" )


  except ValueError:
   t = raw_input( "Invalid input, must be a number. Press yes to continue, no stop")

推荐答案

更仔细地查看代码:

try:
    def di (a, b):
        return  a/b

except ZeroDivisionError:
    print "Divide by 0 Error"

您的try/except块包含整个函数定义:它专门用于定义函数.从调用执行函数时,没有异常块处于活动状态.

Your try/except block includes the entire function definition: it applies specifically to defining the function. There is no exception block active while the function is executing from a call.

改为使用此:

def di (a, b):
    try:
        return  a/b
    except ZeroDivisionError:
        print "Divide by 0 Error"

这篇关于在函数定义周围使用try-except忽略异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆