0

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
Crystal
  • 23
  • 5
  • Can you share minimal code to reproduce your error? Copying and pasting your code and running with python 3.11 doesn't reproduce it. You can also look at this informative post for possible solution: https://stackoverflow.com/questions/46123418/catching-classes-that-do-not-inherit-from-baseexception-is-not-allowed – spo Jul 13 '23 at 18:44
  • The only possible way this could happen is if you defined your own custom `ZeroDivisionError` class, replacing the built-in one. Why are you doing that? – John Gordon Jul 13 '23 at 19:04

2 Answers2

1

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?

tubular
  • 48
  • 5
0

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
crissal
  • 2,547
  • 7
  • 25