python - 为什么即使出现错误,我的 discord.py 机器人中的这些 except 块也不运行?
问题描述
我正在制作一个渲染分形的机器人,但我希望它告诉人们他们是否犯了错误。带有 except 块的部分如下:
try:
MAX_ITER = int(iters)
def mandelbrot(c):
z = complex(float(start[0]),float(start[1]))
n = 0
i = cmath.sqrt(-1)
while abs(z) <= float(brakeoff) and n < MAX_ITER: # number here is the brakeoff
# main formula
z = z ** complex(float(power[0]),float(power[1])) + c
n += 1
return n
except ValueError:
valueerror = discord.Embed(title = "`ValueError` occured. Did you enter a letter or word where there was numeric input?")
valueerror.set_author(name = "Error", icon_url = "https://cdn.discordapp.com/emojis/848700721113333780.png?v=1")
await status.edit(content="", embed=valueerror)
except IndexError:
indexerror = discord.Embed(title = "`IndexError` occured. Did you forget one of the components to a multi-component input?")
indexerror.set_author(name = "Error", icon_url = "https://cdn.discordapp.com/emojis/848700721113333780.png?v=1")
await status.edit(content="", embed=indexerror)
except ZeroDivisionError:
zerodivisionerror = discord.Embed(title = "`ZeroDivisionError` occured. What did I say about how the negative and complex exponents are not supported yet?")
zerodivisionerror.set_author(name = "Error", icon_url = "https://cdn.discordapp.com/emojis/848700721113333780.png?v=1")
await status.edit(content="", embed=zerodivisionerror)
except Exception as error:
error = discord.Embed(title = "An error occured that is not documented in this formula. Here is the error in python: ||" + str(error) + "||")
当出现错误时,它会像往常一样进入终端。但是与错误对应的 except 块没有运行;它没有发布解释错误的嵌入。我尝试了其他错误处理方式,但效果更差。我看到的所有示例都使用了 Discord 错误,而不是像我放在 except 块中的那些正常错误。我怎样才能让它工作?
解决方案
您显示的代码将函数定义放在一个try
块中,但实际上并未调用它。换句话说,只有在定义函数本身except
存在问题时才会输入您的块。(如果您想了解不同之处,Real Python 有一个非常详尽的教程。)
正如终端输出所说,错误没有发生在那里,它发生在Mandelbot.py
文件的第 322 行:m = mandelbrot(c)
. 这是你调用函数的地方。大概你没有try
/在except
那里设置。您的任何代码都没有捕获或处理异常,因此 discord.py 只是将其显示在终端中并继续其业务。
您可能想要的是更多类似于在一个地方定义函数的内容:
MAX_ITER = int(iters)
def mandelbrot(c):
z = complex(float(start[0]),float(start[1]))
n = 0
i = cmath.sqrt(-1)
while abs(z) <= float(brakeoff) and n < MAX_ITER: # number here is the brakeoff
# main formula
z = z ** complex(float(power[0]),float(power[1])) + c
n += 1
return n
然后,无论您在哪里调用它,都将其包装在try
/中except
:
try:
m = mandelbrot(c)
except ValueError:
# (Respond to error)
except IndexError:
# And so on...
这样,您将捕获实际使用函数时发生的任何错误。
推荐阅读
- python - 如何将目录中的图像组织成依赖于数据框列值的类?
- typescript - TypeScript 对动态索引对象的严格成员类型检查
- c - 如何在数组中存储 1 000 000 000 个项目?
- amazon-web-services - 如何从 VPN 访问 AWS ElastiCache (Redis)
- ios - 如何在先前转换的 UIView 上正确地为转换设置动画
- database - 如何删除最后少于500的大文本文件中的行
- dart - 是否可以使 Flutter 中的字符具有相同的宽度?
- python - 熊猫:如何计算日期之前所有出现的id
- ios - UIButtons 没有出现在 UIScrollView 中
- kubernetes - 可以同时拥有 l4 和 l7 ingress-nginx 吗?