Python:如何解决Try Except函数中的TypeError问题?

huangapple go评论62阅读模式
英文:

Python: How to resolve TypeError issue from Try Except function?

问题

我是一个Python新手,我想了解如何在我的Try和Except函数中避免出现TypeError错误,当除数为零时。

给定:

a = 0  # 通常情况下我有一个大于等于1的数字,但我可能会得到0作为输入
b = 0  # 通常情况下我有一个大于等于1的数字,但我可能会得到0作为输入

这是代码:

try:
  h = a / b
except ZeroDivisionError:
  h = 0

这是错误消息:

TypeError: catching classes that do not inherit from BaseException is not allowed
英文:

I'm a python newbie and I'd like to understand how I can avoid getting TypeError error from my Try and Except function with zeros.

Given:

a= 0 (usually I have a number (>=1), but I could get 0 as an input)
b= 0 (usually I have a number (>=1), but I could get 0 as an input)

Here is the code:

try:
  h = a/b
except ZeroDivisionError:
  h = 0

Here is the error message:

TypeError: catching classes that do not inherit from BaseException is not allowed

答案1

得分: 1

错误提示您的自定义异常 ZeroDivisionError 必须继承自 BaseException 类。

class MyZeroDivisionError(Exception):
    pass

话虽如此,此错误随基本 Python 一起提供。实际上,您的片段对我来说可以正常工作,我无法重现 TypeError。您是否可以分享一个可重现的示例或您的其余代码?

英文:

The error is telling you that your custom exception ZeroDivisionError must inherit from the BaseException class.

class MyZeroDivisionError(Exception):
    pass

That said, this error ships with base Python. In fact, your snippet works for me, and I am unable to reproduce the TypeError. Can you either share a reproducible example, or the rest of your code?

答案2

得分: 0

可能你创建了一个名为 class ZeroDivisionError 的类,但它没有继承自 Exception,因此出现了错误。

在使用内置异常的情况下(文档链接:点击这里),最好直接使用内置异常。

>>> try:
...   5/0
... except ZeroDivisionError:
...   print("不能除以零!")
...
不能除以零

编辑:如果要创建一个可以被你的程序捕获的自定义类,可以这样做:

>>> class MyException(Exception):
...   pass
...
>>> try:
...   raise MyException("我的错误消息")
... except MyException as e:
...   print(e)
...
我的错误消息
英文:

Probably you created a class ZeroDivisionError that does not inherit from Exception, thus the error.

In case of a built in exception (docs: click me), it's better that you just use that.

>>> try:
...   5/0
... except ZeroDivisionError:
...   print("Cannot divide by zero!")
...
Cannot divide by zero!

EDIT: to create a custom class that can be caught by your program you can do something like:

>>> class MyException(Exception):
...   pass
...
>>> try:
...   raise MyException("My error message")
... except MyException as e:
...   print(e)
...
My error message

huangapple
  • 本文由 发表于 2023年7月14日 02:31:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76682321.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定