TypeError: exceptions must derive from BaseException in Python

Dung Do Tien Sep 07 2021 41

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.

Have 2 answer(s) found.
  • Đ

    Đặng Thanh Tuấn Sep 07 2021

    You cannot raise a str. Only Exceptions 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

  • H

    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')

     

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close