简体   繁体   中英

TypeError: exceptions must derive from BaseException

I was practicing exception handling from sanfoundary and I got hanged up on a problem which had the problem statement like:

try:
    if '1' != 1:
        raise "someError"
    else:
        print("someError has not occurred")
except "someError":
    print ("someError has occurred")

It is returning an error on running which I am unable to understand, ie,

Traceback (most recent call last):
  File "M:\Prac\test2.py", line 3, in <module>
    raise "someError"
TypeError: exceptions must derive from BaseException

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "M:\Prac\test2.py", line 6, in <module>
    except "someError":
TypeError: catching classes that do not inherit from BaseException is not allowed

In order to raise a custom exception you must implement it first, you cannot raise an exception by just naming it as a string. You can learn more about how to implement custom exceptions in this article .

In this case you can simply call an AssertionError:

try:
    if '1' != 1:
        raise (AssertionError)
except AssertionError:
    print("AssertionError has occurred")
else:
    print("AssertionError has not occurred")

It's interesting to note that placing the else statement after except means that the code in that clause will run only if no error has occurred.

You call also find a list of built-in python exceptions in the documentation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM