Menu
Stuff by Yuki
  • Home
  • Python
  • Power BI
  • Tableau
  • Community
    • Makeover Monday
    • Workout Wednesday
  • 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

  • What are Power BI Dataflows?
  • Calculate the Max Sales Amount for Product
  • Convert DataFrame to Series in Polars
  • Pandas vs Polars – Speed Comparison
  • Polars with DuckDB – Using SQL in Polars

Popular Posts

  • A Running Total Calculation with Quick Measure in Power BI
  • How To Copy And Paste Report Page in Power BI
  • Year-Over-Year Calculation: Time Intelligence in Power BI
  • How to Fill Dates Between Start Date and End Date in Power BI (Power Query)
  • Network Visualizations in Python

connect with me

  • LinkedIn
  • Twitter
  • Github
©2023 Stuff by Yuki | Powered by SuperbThemes & WordPress