TypeError: exceptions must derive from BaseException in Python
Hello you guys, I am a newbie in Python and I'm also studying more about Python.
I have a small assignment, I write a small project and I want to raise some exception when some input not valid. Like this:
mySubject = 'Python'
if len(mySubject) > 3:
raise mySubject + ' programming language is not valid'
But I get an exception TypeError: exceptions must derive from BaseException when I run code above.
Traceback (most recent call last):
File "main.py", line 3, in <module>
raise mySubject + ' programming language is not valid'
TypeError: exceptions must derive from BaseException
And I am using python 3.8.2
Anyone can explain it to me? How can I solve it?
Thanks for any response.
-
Đ6
Đặng Thanh Tuấn Sep 07 2021
You cannot raise a
str
. OnlyExceptions
can be raised.So you better throw an exception with that line and raise it. For example, you could do:
mySubject = 'Python' if len(mySubject) > 3: raise Exception(mySubject + ' programming language is not valid')
OR
mySubject = 'Python' if len(mySubject) > 3: raise ValueError(mySubject + ' programming language is not valid')
Hope this helps
-
H0
Huyền Trần thị Sep 07 2021
It should be an exception type class.
You want to do something like this:
raise RuntimeError(mySubject + ' programming language is not valid')
* Type maximum 2000 characters.
* All comments have to wait approved before display.
* Please polite comment and respect questions and answers of others.