
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Write Custom Python Exceptions with Error Codes and Messages
Custom exceptions in Python allow you to create meaningful error types that fit your application's needs. By adding error codes and error messages to custom exceptions, you can provide structured (organized) information when errors occur.
Although Python has many built-in exceptions, custom exceptions are well-suited to explain specific problems in your program. Including error codes and messages, handling errors, and debugging your code.
Creating a Custom Exception with Error Code
You can create a custom exception by defining a class that inherits from Python's built-in Exception class. This allows you to include additional details, such as a custom error message and an error code, to make error handling more informative.
Example
In this example, we create a custom exception called MyCustomError, which takes an error code and message during initialization -
class MyCustomError(Exception): def __init__(self, code, message): self.code = code self.message = message super().__init__(f"[Error {code}] {message}") def risky_operation(value): if value < 0: raise MyCustomError(1001, "Negative value not allowed") return value * 2 try: result = risky_operation(-5) except MyCustomError as e: print("Caught custom error:", e) print("Error code:", e.code) print("Error message:", e.message)
Here, the exception provides both an error code and a detailed message that can be accessed separately -
Caught custom error: [Error 1001] Negative value not allowed Error code: 1001 Error message: Negative value not allowed
Custom Exceptions for Different Error Types
You can define multiple custom exceptions for different error scenarios by creating subclasses of a base custom exception. This helps in more precise error handling.
Example
In this example, we define a base exception AppError and two subclasses for specific errors, each with its error code and message -
class AppError(Exception): def __init__(self, code, message): self.code = code self.message = message super().__init__(f"[Error {code}] {message}") class ValidationError(AppError): def __init__(self, message): super().__init__(2001, message) class DatabaseError(AppError): def __init__(self, message): super().__init__(3001, message) def validate_data(data): if not isinstance(data, dict): raise ValidationError("Input data must be a dictionary.") def save_to_db(data): raise DatabaseError("Failed to connect to the database.") try: validate_data("invalid data") except AppError as e: print("Caught error:", e) print("Code:", e.code) try: save_to_db({}) except AppError as e: print("Caught error:", e) print("Code:", e.code)
The result produced is as follows -
Caught error: [Error 2001] Input data must be a dictionary. Code: 2001 Caught error: [Error 3001] Failed to connect to the database. Code: 3001
In this way, you can organize exceptions logically and handle them based on their error codes or types.