← All lessons

Your own exceptions

Sign in · Sign up

Lesson 8.4

Ready-made errors don't always fit. Your own error type is a class that inherits from Exception:

class AgeError(Exception):
    pass

pass sits under class because the body of the class has nothing to do yet: the name and the inheritance already say everything.

After that your own error behaves like a built-in one: it is raised with raise and caught with except AgeError as e:

raise AgeError("Age cannot be negative")

Write a function safe_number(raw):

  • if raw is a number, return it as a number ("12" → 12);
  • if it is not a number, raise your own exception NotANumberError with the message That is not a number: <raw>.

Your own error is more precise than a built-in one: in a big program except NotANumberError catches only this case, while except ValueError catches any value error.

Hint

Your own class is two lines: class and pass under it.

Inside the function catch the built-in ValueError from int() and immediately raise your own exception with the text from the task.