Python has a lot of built-in exceptions like ZeroDivisionError, IndexError, ImportError, TypeError, etc but when built-in the exception is not enough to handle our requirements then we create own customized exception. Python allows us to create our exception from the base class exception. To understand it in a better way, let's take an example that raises the error if we will try to find the square root of a negative number. Suppose, we try to find the square root of the -9 then we will get the output in the form of the imaginary number as we all know but here we will write a Python program that raises an error instead of showing the imaginary number and we will handle it by using the try-except statement.
Python有很多内置的异常,例如ZeroDivisionError , IndexError , ImportError , TypeError等,但是当内置的异常不足以满足我们的要求时,我们将创建自己的自定义异常 。 Python允许我们从基类异常中创建异常。 为了更好地理解它,让我们举一个如果发现负数的平方根会引发错误的示例。 假设我们尝试找到-9的平方根,然后我们将以虚数的形式获得输出,但是在这里,我们将编写一个引发错误而不是显示虚数的Python程序,我们将通过使用try-except语句来处理它。
Before going to write the Python program, we will the syntax of the try-except statement,
在编写Python程序之前,我们将使用try-except语句的语法 ,
try:
#statement or line of code
except typeofError:
#statement or line of code
Now, we will see the program in which we will create the user-defined exception to overcome the problem of imaginary number and again we handle it by using the try-except statement.
现在,我们将看到一个程序,其中将创建用户定义的异常来克服虚数的问题,然后再次使用try-except语句对其进行处理。
Program:
程序:
# creating child class from base class Exception
class Error(Exception):
pass # dummy function
class InvalidNumberError(Error):
def __init__(self,statement,s): # constructer
self.statement=statement
self.s=s
number=int(input('Enter a Number: '))
try:
if number<1: # condition checking
raise InvalidNumberError('You have entered a negative number.',number)
else:
print('The square root of the number:',(number)**0.5)
except InvalidNumberError as e: #user defined exception handling
print(e.statement)
Output
输出量
RUN 1:
Enter a Number: 5
The square root of the number: 2.23606797749979
RUN 2:
Enter a Number: -5
You have entered a negative number.
翻译自: https://www.includehelp.com/python/user-defined-exception.aspx