Menu
Stuff by Yuki
  • Home
  • Data Engineering
    • Python
  • Business Intelligence
    • Power BI
    • Tableau
  • Perspectives
  • About
  • Contact
Stuff by Yuki

Create Custom Exceptions in Python

Posted on October 22, 2022October 28, 2022

What are Exceptions in Python?

Here’s what Python.org says about an exception in Python:

Even if a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute it. Errors detected during execution are called exceptions and are not unconditionally fatal.

Reference: https://docs.python.org/3/tutorial/errors.html

If I put this simply, an exception is a flag that disrupts the typical flow of the program, but doesn’t stop the program itself. It can basically raise errors or handle each case by case.

Create Custom Exceptions in Python

There are cases where you want to raise your own exceptions for your particular case. And there is an easy way to do that in Python. You define a custom exception class that inherits the base Exception class. And you just use that in your code. Here’s an example:

Copy Copied Use a different Browser

class YourOwnException(Exception):
    pass

Copy Copied Use a different Browser

from custom_exceptions import YourOwnException

try:
    raise YourOwnException('This is your own custom exception!')
except YourOwnException as e:
    print(e)

"""
Output:

This is your own custom exception!

"""

That’s it! Now you learned how to create a custom exception in Python. You can copy code from this github repo.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • Where I’m Headed in the Next 5 Years
  • Open-Source vs Vendor Data Tools
  • Developing the Habit of Writing
  • How to Inspect and Optimize Query Plans in Python Polars
  • Learn Python Polars with Polars Cookbook

Popular Posts

  • A Running Total Calculation with Quick Measure in Power BI
  • A Complete Guide to Git Integration in Power BI
  • How To Copy And Paste Report Page in Power BI
  • Handling Missing Values in Polars
  • How to Convert String to Date or Datetime in Polars

connect with me

  • LinkedIn
  • Twitter
  • Github
  • Website

Search Articles

©2025 Stuff by Yuki | Powered by SuperbThemes