Python BaseException – Tutorial with Examples

Python BaseException - Tutorial with Examples

Python programming is all about exception handling. One of the fundamental concepts of exception handling in Python is BaseException. All exception classes in Python are derived from BaseException. In Python, exceptions are objects just like in any other programming language, and they are created when a program encounters an error.

This article will help you understand the BaseException class in depth. We will discuss its properties and methods through different examples.

What is BaseException?

As mentioned earlier, BaseException is the base class used for all built-in exceptions such as KeyError, ImportError, etc. It is a subclass of the object class and it defines the core of Python’s exception handling mechanism.

BaseException is derived from Exception, which is derived from the object class at the top of the class hierarchy.

Properties of BaseException

BaseException has several properties that can be used to get details regarding the raised exception, some of which are listed below:

  • args: A tuple containing the exception arguments
  • message: A string containing the exception message
  • errno: An integer specifying the error code

Methods of BaseException

Below are some of the commonly used methods of BaseException:

  • __str__(self): This method is used to convert the exception instance to a string.
  • __repr__(self): This method is used to generate a string that can recreate the exception instance.

Examples of BaseException

Example 1: Handling a simple exception

Let’s say you are writing a program that is dividing two numbers. As is normal, you would guard against the user entering a zero as a divisor. Here’s how we’d do it:

a = 10
b = 0

 try:
    print(a / b)
 except BaseException as ex:
    print(f"Error: {ex}")

Output:

Error: division by zero

Here, we caught the exception and printed the error message. Note that the basic format of handling an exception hasn’t changed. The only addition is the ‘as’ keyword, which is used to capture the exception object.

Example 2: Using the args property

Assume that we caught the exception, but we want more information on the error to display to the user. We can use the args property to get the exception arguments:

a = 10
b = 0

try:
    print(a / b)
except BaseException as ex:
    print(f"Error: {ex.args}")

Output:

Error: ('division by zero',)

Here, we printed the exception.message property. ‘

The args property returns a tuple containing the arguments passed to the exception constructor. In this case, the arguments passed for the ZeroDivisionError were “division by zero”.

Example 3: Using the __str__() method

We can also use the str() method to get information about the exception.

a = 10
b = 0

try:
    print(a / b)
except BaseException as ex:
    print(f"Error: {str(ex)}")

Output:

Error: division by zero

In the above example, we used the str() method to convert the exception object to a string that can be printed directly.

Example 4: Using the __repr__() method

The repr() method returns the string representation of the exception object.

a = 10
b = 0

try:
    print(a / b)
except BaseException as ex:
    print(f"Error: {repr(ex)}")

Output:

Error: ZeroDivisionError('division by zero',)

In the above example, we used the repr() method to get a detailed string representation of the exception object. This is useful when we are debugging.

Example 5: Raising an exception

In Python, we can raise an exception using the “raise” statement. In this example, we are manually raising an exception:

def foo(x):
    if x == 0:
        raise Exception('x cannot be 0')
    else:
        return 100 / x

try:
    print(foo(0))
except BaseException as ex:
    print(f"Error: {ex}")

Output:

Error: x cannot be 0

In the above example, when we pass 0 to foo(), it will throw an exception, and we will catch that exception using BaseException.

Example 6: Catching Python exceptions

Here, we will use except statement to handle Python built-in exceptions such as NameError, AttributeError, etc.:

try:
    print(undefined_variable)
except BaseException as ex:
    print(f"Error: {ex}")

Output:

Error: name 'undefined_variable' is not defined

In this example, since “undefined_variable” is not defined, Python will throw a NameError. We caught the exception and printed its message.

Conclusion

BaseException is a key class in Python’s exception handling mechanism. It is a parent class for all built-in exceptions in Python. In this article, we covered some of the methods and properties of BaseException with different examples.

Leave a Reply

Your email address will not be published. Required fields are marked *