0
0
Pythonprogramming~5 mins

Custom error messages in Python

Choose your learning style9 modes available
Introduction

Custom error messages help you explain what went wrong in your program in a clear and friendly way.

When you want to tell the user why their input is not accepted.
When you want to make debugging easier by showing specific problems.
When you want to stop the program if something important is missing or wrong.
When you want to guide someone using your code on how to fix errors.
When you want to replace confusing default error messages with simple ones.
Syntax
Python
raise ExceptionType("Your custom error message here")

You can use built-in exceptions like ValueError, TypeError, or create your own.

The message inside quotes explains the error in simple words.

Examples
This stops the program and shows a message if a value is wrong.
Python
raise ValueError("Please enter a positive number")
This checks a condition and raises an error with a custom message.
Python
if age < 0:
    raise ValueError("Age cannot be negative")
You can create your own error type and use it with a message.
Python
class MyError(Exception):
    pass

raise MyError("Something special went wrong")
Sample Program

This program checks if the temperature is below absolute zero. If yes, it stops and shows a clear error message.

Python
def check_temperature(temp):
    if temp < -273.15:
        raise ValueError("Temperature cannot be below absolute zero!")
    print(f"Temperature is {temp} degrees Celsius.")

try:
    check_temperature(-300)
except ValueError as e:
    print(f"Error: {e}")
OutputSuccess
Important Notes

Always make your error messages clear and helpful.

Use try-except blocks to catch and handle errors gracefully.

Custom errors improve user experience and debugging.

Summary

Custom error messages explain problems clearly.

Use raise with a message to stop the program when needed.

Catch errors with try-except to handle them nicely.