Home > Back-end >  Can I do this in python? [closed]
Can I do this in python? [closed]

Time:09-18

Can i do this in python?:

a = input("Name.sign: ")
if not ".firstname" in a:
    raise NameError(f"{a} is not defined") from a

The from a, if i can do this, it raise: TypeError: exception causes must derive from BaseException

CodePudding user response:

Using from only can get the error from a BaseException, like:

>>> a = 1
>>> raise NameError(f"{a} is not defined") from BaseException(a)
BaseException: 1

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<pyshell#71>", line 1, in <module>
    raise NameError(f"{a} is not defined") from BaseException(a)
NameError: 1 is not defined
>>> 

Usually the expression of raise ... from ... is used for excepted exceptions, like:

>>> >>> try:
    raise TypeError('blah blah blah')
except TypeError as exception:
    raise NameError(f"a is not defined") from exception

Traceback (most recent call last):
  File "<pyshell#81>", line 2, in <module>
    raise TypeError('blah blah blah')
TypeError: blah blah blah

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<pyshell#81>", line 4, in <module>
    raise NameError(f"a is not defined") from exception
NameError: a is not defined
>>> 

So that it raises both the original and manual excpetions.

CodePudding user response:

you can use assert like below and you get error in AssertionError.

a = input("Name.sign: ")
assert ".firstname" in a
print(f"{a} is not defined")
  • Related