Python User-Defined Exceptions: Customizing Error Handling

thumb_up 1  ·  sell Python user-defined exceptions, Custom error handling in Python, Defining custom exceptions in Python code

Python also allows you to create your own exceptions by deriving classes from the standard built-in exceptions.

Here is an example that has a user-defined MyException class. Here, a class is created that is subclassed from base Exception class. This is useful when you need to display more specific information when an exception is caught.

In the try block, the user-defined exception is raised whenever value of num variable is less than 0 or more than 100 and caught in the except block. The variable e is used to create an instance of the class MyException.

Example

 
class MyException(Exception): "Invalid marks" pass num = 10 try: if num <0 or num>100: raise MyException except MyException as e: print ("Invalid marks:", num) else: print ("Marks obtained:", num)

Output

For different values of num, the program shows the following output −

Marks obtained: 10
Invalid marks: 104
Invalid marks: -10



The End! should you have any inquiries, we encourage you to reach out to the Vercaa Support Center without hesitation.

Was this answer helpful?

Related Articles

description

Exploring Python's Key Characteristic

Python is a feature rich high-level, interpreted, interactive and object-oriented scripting language. This tutorial will list down some of…

arrow_forward
description

Comparing Python and C++

Both Python and C++ are among the most popular programming languages. Both of them have their advantages and disadvantages. In this…

arrow_forward
description

Creating a Python Hello World Program

This tutorial will teach you how to write a simple Hello World program using Python Programming language. This program will make use of…

arrow_forward
description

Python's Versatile Application Domains

Python is a general-purpose programming language. It is suitable for development of wide range of software applications. Over last few…

arrow_forward
description

Understanding the Python Interpreter

Python is an interpreter-based language. In a Linux system, Python's executable is installed in /usr/bin/ directory. For Windows, the…

arrow_forward
arrow_back « Back