python自定义异常_Python自定义异常

python自定义异常

In this tutorial we are going to learn about Python Custom Exception. If you don’t know about Python Exception Handling, we suggest you to read the previous tutorial.

在本教程中,我们将学习Python自定义异常。 如果您不了解Python异常处理,建议您阅读前面的教程

Python自定义异常 (Python Custom Exception)

In Python Exception Handling Tutorial, we discussed about what exception is. Basically exception means when things are not going accordingly. We talked about different kind of built-in exceptions in the previous tutorial. However sometimes built-in exceptions are not enough for our need, then we can define our own custom exception.

在Python异常处理教程中,我们讨论了什么是异常。 基本上,异常是指情况没有相应地发展。 在上一教程中,我们讨论了不同类型的内置异常。 但是,有时内置的异常不足以满足我们的需要,那么我们可以定义自己的自定义异常。

使用assert语句的Python自定义异常 (Python Custom Exception using assert statement)

Using assert statement you can initially create your own exception. Basically assert statement check for a condition. If the condition is not met then it will throw AssertionError. Suppose you wrote a function where you take age as an argument. You don’t want to let programmers use the function if the age is less the 18. So the function would be.

使用assert语句,您可以最初创建自己的异常。 基本上断言语句检查条件。 如果不满足条件,则将抛出AssertionError。 假设您编写了一个函数,以年龄作为参数。 如果年龄小于18岁,您不想让程序员使用该函数。

def input_age(age):
   try:
       assert int(age) > 18
   except ValueError:
       return 'ValueError: Cannot convert into int'
   else:
       return 'Age is saved successfully'


print(input_age('23'))  # This will print
print(input_age(25))  # This will print
print(input_age('nothing'))  # This will raise ValueError which is handled
print(input_age('18'))  # This will raise AssertionError and the the program collapse
print(input_age(43))  # This will not print

The output of the following program will be

以下程序的输出将是

Age is saved successfully
Age is saved successfully
ValueError: Cannot convert into int

Traceback (most recent call last):
  File "/home/imtiaz/ExceptionHandling.py", line 13, in 
    print(input_age('18'))  # This will raise AssertionError the the program collapse
  File "/home/imtiaz/ExceptionHandling.py", line 3, in input_age
    assert int(age) > 18
AssertionError

引发异常 (Raising an Exception)

Your can raise an existing exception by using raise keyword. So, you just simply write raise keyword and then the name of the exception. If we modify the previous code, we get

您可以使用raise关键字引发现有异常。 因此,您只需要简单地写上raise关键字,然后写上异常的名称即可。 如果我们修改前面的代码,我们得到

def input_age(age):
   try:
       if(int(age)<=18):
           raise ZeroDivisionError
   except ValueError:
       return 'ValueError: Cannot convert into int'
   else:
       return 'Age is saved successfully'


print(input_age('23'))  # This will execute properly
print(input_age('18'))  # This will not execute properly

The output of the code will be

代码的输出将是

Age is saved successfully
Traceback (most recent call last):
  File "/home/imtiaz/ExceptionHandling.py", line 12, in 
    print(input_age('18'))  # This will not print
  File "/home/imtiaz/ExceptionHandling.py", line 4, in input_age
    raise ZeroDivisionError
ZeroDivisionError

Though, the exception was not due to divide by zero, still we see it. Because we raised ZeroDivisionError.

虽然,该异常不是由于被零除,但我们仍然看到了。 因为我们提出了ZeroDivisionError。

Python自定义异常类 (Python Custom Exception Class)

Python allow programmers to create their own exception class. Exceptions should typically be derived from the Exception class, either directly or indirectly. In the following example, we create custom exception class UnderAge that is derived from the base class Exception.

Python允许程序员创建自己的异常类。 通常,异常应该直接或间接地从Exception类派生。 在以下示例中,我们创建自基类Exception派生的自定义异常类UnderAge

Again, in another method we raised the UnderAge exception if the condition is not met. The following code will give you some insight about the idea.

同样,在另一种方法中,如果不满足条件,则引发UnderAge异常。 以下代码将使您对该想法有所了解。

class UnderAge(Exception):
   pass

def verify_age(age):
   if int(age) < 18:
       raise UnderAge
   else:
       print('Age: '+str(age))

# main program
verify_age(23)  # won't raise exception
verify_age(17)  # will raise exception

And the output will be

输出将是

So, that’s all about Python custom Exception. Hope, everything is easier to understand. For any further query, please use the comment box below.

所以,这就是关于Python自定义异常的全部内容。 希望,一切都更容易理解。 如有其他查询,请使用下面的评论框。

Reference: Python User Defined Exception Official Documentation

参考: Python用户定义的异常官方文档

翻译自: https://www.journaldev.com/14454/python-custom-exception

python自定义异常