精华内容
下载资源
问答
  • python 自定义异常

    2020-11-16 13:05:27
    python 自定义异常

    python 自定义异常

    参考文章:

    (1)python 自定义异常

    (2)https://www.cnblogs.com/alplf123/p/8269390.html


    备忘一下。


    展开全文
  • python自定义异常_Python自定义异常

    千次阅读 2020-07-05 22:24:52
    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自定义异常

    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自定义异常

    展开全文
  • Python 自定义异常

    2020-12-29 17:09:15
    Python 自定义异常 #1.用户自定义异常类型 class TdmsFileMissedExceptin(Exception): "this is user's Exception for check the length of name " def __init__(self,path): self.path = path def __str__...

    Python 自定义异常

     

    #1.用户自定义异常类型
    class TdmsFileMissedExceptin(Exception):
        "this is user's Exception for check the length of name "
        def __init__(self,path):
            self.path = path
        def __str__(self):
            print("The tdms files in "+str(self.path)+"is missed!")
    展开全文
  • python自定义异常

    2019-04-23 19:42:22
    python自定义异常: class BaseError(Exception): def __init__(self,ErrorInfo): super().__init__(self) #初始化父类 self.errorinfo=ErrorInfo def __str__(self): return self.errorinfo...

    python自定义异常:

    class BaseError(Exception):
        def __init__(self,ErrorInfo):
            super().__init__(self) #初始化父类
            self.errorinfo=ErrorInfo
        def __str__(self):
            return self.errorinfo

    接住异常,在控制台打印异常信息:

    try:
        raise BaseError('异常')
    except BaseError as e:
        print(e)

    直接抛出异常,中断程序执行:

    raise BaseError('异常')

     

    展开全文
  • Python自定义异常

    2020-11-08 14:56:34
    (2) 不够用,用户自定义异常, 首先看看python的异常继承树 我们可以看到python的异常有个大基类。然后继承的是Exception。所以我们自定义类也必须继承Exception。 程序出现错误,会自动引发异常,Python也允许使用...
  • #自定义异常类class MyException(Exception):passdef exextp_01():try:#come code herelist = ['java','python','php']raise MyException #通过异常名字抓取自定义异常except:print 'no thie is variabe'print '...
  • 日常开发中,当系统提供的异常类型不能满足开发的需求时,就需要自己创建一个新的异常类来拥有自己的异常。 自定义异常类继承自 Exception 类,可以直接继承,或者间接继承。
  • 主要介绍了python自定义异常实例详解的相关资料,需要的朋友可以参考下
  • 今天小编就为大家分享一篇python 自定义异常和异常捕捉的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
  • python自定义异常实例

    2018-06-22 17:01:49
    本实例是一个关于python自定义异常的实例,供大家学习和交流

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 69,901
精华内容 27,960
关键字:

python自定义异常

python 订阅