Skip to main content

Raising Custom Errors in Python

 


 

Raising Custom Errors in Python          show

Raising Custom Errors in Python

In Python, you can define your own exceptions by creating a new class that inherits from the built-in Exception class. This is useful when you need to create specific error types that can provide more information about what went wrong in your code.

1. Defining a Custom Exception

To define a custom exception, create a new class that inherits from Exception.


# Define a custom exception
class CustomError(Exception):
    pass
    

2. Raising a Custom Exception

Use the raise keyword to raise the custom exception.


# Raise a custom exception
raise CustomError("This is a custom error message")
    

3. Handling a Custom Exception

Use a try block to catch and handle the custom exception.


# Handle a custom exception
try:
    raise CustomError("This is a custom error message")
except CustomError as e:
    print(e)

# Output:
# This is a custom error message
    

4. Adding Attributes to Custom Exceptions

You can add attributes to your custom exceptions to provide additional information about the error.


# Custom exception with attributes
class CustomError(Exception):
    def __init__(self, message, code):
        self.message = message
        self.code = code
        super().__init__(message)

try:
    raise CustomError("An error occurred", 500)
except CustomError as e:
    print(e.message, "Error Code:", e.code)

# Output:
# An error occurred Error Code: 500
    

5. Using Custom Exceptions in Functions

Custom exceptions can be used in functions to signal specific error conditions.


# Function using custom exceptions
def check_positive(number):
    if number < 0:
        raise CustomError("Number must be positive", 400)
    return number

try:
    check_positive(-10)
except CustomError as e:
    print(e.message, "Error Code:", e.code)

# Output:
# Number must be positive Error Code: 400
    

Popular posts from this blog

Inheritance in Python

  Learning Sections          show Inheritance in Python Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a class to inherit attributes and methods from another class. The class that inherits is called the child class or subclass, and the class being inherited from is called the parent class or superclass. Basic Inheritance In Python, a child class inherits from a parent class by specifying the parent class in parentheses after the child class name. Example: class Animal : def __init__ ( self , name ): self . name = name def speak ( self ): raise NotImplementedError ( "Subclass must implement this method" ) class Dog ( Animal ): def speak ( self ): return "Woof!" class Cat ( Animal ): def speak ( self ): return "Meow!" # Create instances of Dog and Cat dog = Dog ( "Buddy" ) cat = Cat ( "Whiskers" ...

Introduction to OOPs in Python

  Learning Sections          show Introduction to Object-Oriented Programming (OOP) Object-Oriented Programming (OOP) is a programming paradigm that organizes software design around objects rather than actions and data rather than logic. It revolves around the concept of "objects", which are instances of classes. These objects encapsulate data, in the form of attributes or properties, and behaviors, in the form of methods or functions. OOP promotes modularity, reusability, and extensibility in software development. Key Concepts of OOP: Class: A class is a blueprint or template for creating objects. It defines the attributes (data) and methods (functions) that will characterize any object instantiated from that class. Object: An object is an instance of a class. It is a concrete realization of the class blueprint, containing actual values instead of placeholders for attributes. Encapsulation: Encapsulation is ...

Generators in Python

  Learning Sections          show Generators in Python Generators are a special type of iterator in Python that allow you to iterate over a sequence of items without storing them all in memory at once. They are useful for generating large sequences of data on-the-fly, or for processing data in a memory-efficient manner. Creating Generators In Python, generators are created using generator functions or generator expressions: # Generator function def my_generator ( n ): for i in range ( n ): yield i # Generator expression my_generator = ( i for i in range ( 10 )) A generator function uses the yield keyword to yield values one at a time, while a generator expression creates an anonymous generator. Iterating Over Generators You can iterate over the values produced by a generator using a for loop: for value in my_generator ( 5 ): print ( value ) This w...