Python Raising Exceptions and Custom Exceptions Explained
Use raise when your code needs to stop immediately because something is wrong, and use a custom exception when built-in errors do not describe the problem clearly enough. In Python, raising the right exception makes bugs easier to find, tests easier to write, and error messages easier to understand. This article shows how raise works, how to create your own exception class, and how to use both well.
Difficulty: Beginner
Helpful to know first: basic Python syntax, how functions return values, and how try and except work.
How Python Raises an Exception
Raising an exception means telling Python to stop normal execution and signal an error condition. The simplest form is raise followed by an exception object, such as ValueError or TypeError.
Here is the smallest useful example:
age = -3
if age < 0:
raise ValueError("age must be non-negative")
print("This line never runs")Python stops at the raise statement and creates a ValueError. The message explains what went wrong, and the print() call after it does not run.
Most raised exceptions are used for validation: a function checks its input, and if the input is invalid, it raises an exception instead of returning a wrong result.
Raising Built-in Exceptions With the Right Meaning
Python already gives you many exception types. Pick one that matches the problem instead of always using Exception or RuntimeError.
Use ValueError when the value is wrong
If the type is correct but the value is invalid, ValueError is usually the right choice.
def square_root(number):
if number < 0:
raise ValueError("number must be 0 or greater")
return number ** 0.5
print(square_root(9))
# Output: 3.0This function accepts a number, checks whether the value is valid, and then returns the result. If the input is negative, it raises a clear error before doing the calculation.
Use TypeError when the type is wrong
If the caller passes the wrong kind of object, TypeError is a better fit.
def repeat_message(message, count):
if not isinstance(count, int):
raise TypeError("count must be an int")
return message * count
print(repeat_message("hi", 3))
# Output: hihihiThis code separates a type problem from a value problem. That distinction helps the caller understand whether to change the data type or just the data itself.
Use KeyError, IndexError, and other specific errors when they match
When your code is working with a mapping or sequence, the built-in exceptions can describe the exact problem better than a general error.
prices = {"apple": 1.25, "banana": 0.75}
if "pear" not in prices:
raise KeyError("pear")
print(prices["apple"])
# Output: 1.25Specific built-in exceptions make it easier to catch only the failures you expect, while letting unrelated bugs still surface.
How to Create a Custom Exception Class
A custom exception is a class you define yourself, usually by inheriting from Exception. You use it when built-in errors do not say enough about your domain or your application rules.
A minimal custom exception looks like this:
class InvalidEmailError(Exception):
pass
def check_email(email):
if "@" not in email:
raise InvalidEmailError("email must contain @")
return email
print(check_email("[email protected]"))
# Output: [email protected]The class name tells readers and tests exactly what failed. Instead of catching a generic error, calling code can catch InvalidEmailError and react only to that problem.
Custom exceptions are usually small. They often contain no methods at all, just a meaningful name.
Add a message when the exception needs context
Sometimes you want the exception to include details such as a user name, a file path, or the invalid value. You can store that data on the object and build a useful message.
class InsufficientBalanceError(Exception):
def __init__(self, balance, amount):
self.balance = balance
self.amount = amount
super().__init__(
f"cannot withdraw {amount}; balance is {balance}"
)
def withdraw(balance, amount):
if amount > balance:
raise InsufficientBalanceError(balance, amount)
return balance - amount
print(withdraw(50, 20))
# Output: 30This version stores the values that caused the error, which can help when logging or testing. The message is readable for humans, and the attributes are useful for code.
Raising an Exception at the Right Time
You usually raise an exception as soon as a function knows it cannot continue safely. That makes the failure local and easier to debug.
For example, validate function arguments at the top of the function:
def divide(numerator, denominator):
if denominator == 0:
raise ZeroDivisionError("denominator must not be zero")
return numerator / denominator
print(divide(10, 2))
# Output: 5.0This is better than computing with invalid data and failing later in a harder-to-read place. The earlier the exception is raised, the easier it is to understand the cause.
A function should raise an exception when it cannot complete its job correctly, not just to show that a condition exists. If the code can continue in a safe and clear way, returning a value may be better than raising one.
Using raise with try and except
You often raise an exception in one function and catch it in another. The code that detects the problem should raise it; the code that can recover should catch it.
def parse_age(text):
if not text.isdigit():
raise ValueError("age must contain digits only")
return int(text)
try:
age = parse_age("19x")
except ValueError as error:
print("Could not parse age:", error)
# Output: Could not parse age: age must contain digits onlyThe except block can choose a fallback action, display a message, or log the problem. The exception object itself is available as error, so you can print or inspect its message.
How Exceptions Behave in Detail
Raised exceptions immediately stop the current path of execution unless something catches them. They also carry a traceback, which is Python’s record of where the error happened and how the program reached that point.
A few important details matter in real code:
- Only exceptions derived from BaseException can be raised, but application code should almost always inherit from Exception.
- A custom exception does not need special methods unless you want extra data or custom formatting.
- Catching Exception is broad. It may hide bugs if you use it too early or too often.
- Raising the wrong exception type can make debugging harder because callers may handle the wrong case.
Python also supports exception chaining. If one error happens because of another, you can preserve both causes.
def load_port(text):
try:
return int(text)
except ValueError as error:
raise ValueError("port must be a number") from error
try:
load_port("abc")
except ValueError as error:
print(error)
# Output: port must be a numberThe new error keeps the user-friendly message, and the original exception is still attached for debugging. That is useful when you want to translate a low-level failure into a higher-level message.
Predict the Output
What happens when a function raises before returning?
def show_total(count):
if count < 1:
raise ValueError("count must be at least 1")
return count * 2
print(show_total(0))What does this print?
Show answer
It does not print a number. Python raises ValueError on the second line inside the function, so print() never gets a return value.
# Trace
# 1. show_total(0) is called
# 2. count < 1 is true
# 3. ValueError is raised
# 4. the return statement is skipped
# 5. print() never prints a resultWhat exception type is most appropriate here?
def set_percentage(value):
if value > 100:
raise ValueError("value must be 100 or less")
return value
print(set_percentage(120))What happens?
Show answer
Python raises ValueError. The type is correct because 120 is a number, but the value is outside the allowed range. The function returns nothing, so print() never prints a result.
Common Mistakes When Raising Exceptions
Using Exception when a specific built-in type is better
Many beginners write raise Exception(...) because it seems simple. It works, but it gives less information to both humans and calling code.
Problem: A generic exception hides the real category of the problem, so callers cannot easily tell whether the issue is a bad value, bad type, or something else.
def parse_score(score):
if score < 0:
raise Exception("score must be non-negative")
return scoreFix: Use the most specific built-in exception that matches the problem.
def parse_score(score):
if score < 0:
raise ValueError("score must be non-negative")
return scoreThe corrected version is clearer because ValueError tells readers that the problem is the value, not the function itself.
Raising a string instead of an exception object
Python 3 does not allow raising plain strings. The object after raise must be an exception instance or exception class.
Problem: The code tries to raise text directly, so Python reports a type error instead of your intended message.
def check_name(name):
if not name:
raise "name is required"Fix: Raise a real exception object such as ValueError.
def check_name(name):
if not name:
raise ValueError("name is required")The corrected version works because Python knows how to build and propagate exception objects.
Catching the wrong exception and hiding the bug
If you catch too broadly, you may hide errors you did not mean to handle.
Problem: The code catches every Exception, so programming mistakes like a misspelled variable name can disappear behind a misleading message.
try:
print(missing_name)
except Exception:
print("Something went wrong")Fix: Catch the specific error you expect.
try:
print(missing_name)
except NameError:
print("Name not defined")The fixed version works because it handles only the error you meant to recover from.
Defining a custom exception that does not inherit from Exception
Custom exceptions should usually inherit from Exception. If they do not, they may behave unexpectedly or be awkward to catch.
Problem: The class is not part of Python’s normal exception hierarchy, so it does not behave like a standard application error.
class BadInputError:
pass
raise BadInputError("invalid input")Fix: Inherit from Exception or one of its subclasses.
class BadInputError(Exception):
pass
raise BadInputError("invalid input")The corrected version works because Python recognizes it as a normal, catchable exception type.
Find the Bug
A hurried developer wrote this function to validate a username. It looks reasonable, but one part of the exception logic is wrong. Find the bug.
class UsernameError(Exception):
pass
def validate_username(username):
if not username:
raise Exception("username is required")
if len(username) < 3:
raise UsernameError("username is too short")
print(validate_username("al"))What is wrong with this code, and how would you fix it?
Show answer
The bug is that the first error uses a generic Exception instead of the custom UsernameError. That makes the API inconsistent: one validation path raises a domain-specific error, and another raises a catch-all error.
Fixed code:
class UsernameError(Exception):
pass
def validate_username(username):
if not username:
raise UsernameError("username is required")
if len(username) < 3:
raise UsernameError("username is too short")
print(validate_username("al"))The fixed version works because callers can now catch UsernameError for every username validation problem.
When to Use a Custom Exception Instead of a Built-in One
Use a custom exception when the failure belongs to your domain and a built-in error would be too vague. Use a built-in exception when the problem already has a standard meaning in Python.
| Situation | Better choice | Why |
|---|---|---|
| Invalid numeric value | ValueError | Python already uses it for bad values. |
| Wrong argument type | TypeError | It says the caller passed the wrong type. |
| Business rule specific to your app | Custom exception | The name can describe your domain clearly. |
| Missing dictionary key | KeyError | Standard meaning for lookup failures. |
A good custom exception name often ends with Error, such as PaymentDeclinedError or InventoryUnavailableError. That naming pattern is readable and familiar to Python developers.
A custom exception is not for normal control flow. If the situation is expected and common, a return value, None, or a boolean is often a better design than raising an error.
Predict the Output
What happens if you catch the custom exception?
class TooYoungError(Exception):
pass
try:
raise TooYoungError("must be 18")
except TooYoungError as error:
print(error)What does this print?
Show answer
It prints must be 18. The exception is raised immediately, then caught by the matching except block, and the message stored in the exception is printed.
Try It Yourself
- Write a custom exception named NegativeDepositError.
- Create a function named deposit that accepts a current balance and a deposit amount.
- If the deposit amount is less than zero, raise NegativeDepositError with the message "deposit must be non-negative".
- If the amount is valid, return the new balance.
- Call the function twice: once with a valid amount and once with an invalid amount inside a try / except block.
Expected output:
120
deposit must be non-negativeHint: Define the custom exception first, then use raise inside the function when the amount is below zero.
Show solution
class NegativeDepositError(Exception):
pass
def deposit(balance, amount):
if amount < 0:
raise NegativeDepositError("deposit must be non-negative")
return balance + amount
print(deposit(100, 20))
try:
print(deposit(100, -5))
except NegativeDepositError as error:
print(error)Summary
- Use raise to stop execution when a function cannot continue safely.
- Choose the most specific built-in exception that matches the problem, such as ValueError or TypeError.
- Create a custom exception by inheriting from Exception.
- Give custom exceptions clear names that describe your domain or rule.
- Raise errors as early as possible so the cause is easy to find.
- Catch only the exceptions you expect to handle.
Next, learn try and except in more depth, including how to handle multiple exception types and how exception chaining works.