1

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, i.e.,

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
Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47
Vaibhav Raj
  • 11
  • 1
  • 2
  • 1
    `raise "someError"` is wrong because you musy raise an `Exception` object but you're actually raising a `str` object. Does this answer your question? [Proper way to declare custom exceptions in modern Python?](https://stackoverflow.com/questions/1319615/proper-way-to-declare-custom-exceptions-in-modern-python) – Pranav Hosangadi Mar 22 '21 at 18:24

1 Answers1

3

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.

Luiz
  • 31
  • 1