CodeBlanks Logo Icon CodeBlanks

Custom exceptions

Learn to write custom exceptions with class MyError(Exception).

Custom exception class

To define your own error you subclass Exception:

class StokError(Exception):
    pass

raise StokError("stok bitti")

Here a new error type called StokError is created. The pass body lets it inherit all of Exception's behaviour. Now you can raise it with raise StokError(...) and catch it with except StokError.

This lets you clearly report domain-specific errors.

Raising and catching custom exceptions

You raise your custom exception with raise and catch it with except — just like built-in errors:

class StokError(Exception):
    pass

try:
    raise StokError("stok bitti")
except StokError as e:
    print(e)  # stok bitti

Here as e gives you access to the error message. Custom exceptions let calling code distinguish errors by type.

In large projects each module defines its own exception class.

Practice Define and catch StokError

Define class StokError(Exception): with pass in the body. Inside a try: block write raise StokError("stok bitti"). Inside an except StokError as e: block write print(e).

Starter code

main.py
# derive StokError from Exception
# raise it and catch with except

Sample solution

main.py
class StokError(Exception):
    pass

try:
    raise StokError("stok bitti")
except StokError as e:
    print(e)

Expected output

stok bitti

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the custom exception definition

Question
class StokError(____):
    pass
Answer
class StokError(Exception):
    pass

Explanation: Custom exceptions derive from Exception.

2 Which class do custom exceptions derive from?

  • BaseException
  • Exception Correct answer
  • object
  • Error

Explanation: Custom exceptions derive from Exception; so except Exception catches them.

3 Match custom exceptions

Term Meaning
class StokError(Exception) Custom exception
pass Empty body
raise StokError Raising
except StokError as e Catching

All lessons in Beginner