Manually raising (throwing) an exception in Python

前端 未结 8 1191
长发绾君心
长发绾君心 2020-11-22 03:38

How can I raise an exception in Python so that it can later be caught via an except block?

8条回答
  •  梦谈多话
    2020-11-22 04:14

    In Python3 there are 4 different syntaxes for rasing exceptions:

    1. raise exception 
    2. raise exception (args) 
    3. raise
    4. raise exception (args) from original_exception
    

    1. raise exception vs. 2. raise exception (args)

    If you use raise exception (args) to raise an exception then the args will be printed when you print the exception object - as shown in the example below.

      #raise exception (args)
        try:
            raise ValueError("I have raised an Exception")
        except ValueError as exp:
            print ("Error", exp)     # Output -> Error I have raised an Exception 
    
    
    
      #raise execption 
        try:
            raise ValueError
        except ValueError as exp:
            print ("Error", exp)     # Output -> Error 
    

    3.raise

    raise statement without any arguments re-raises the last exception. This is useful if you need to perform some actions after catching the exception and then want to re-raise it. But if there was no exception before, raise statement raises TypeError Exception.

    def somefunction():
        print("some cleaning")
    
    a=10
    b=0 
    result=None
    
    try:
        result=a/b
        print(result)
    
    except Exception:            #Output ->
        somefunction()           #some cleaning
        raise                    #Traceback (most recent call last):
                                 #File "python", line 8, in 
                                 #ZeroDivisionError: division by zero
    

    4. raise exception (args) from original_exception

    This statement is used to create exception chaining in which an exception that is raised in response to another exception can contain the details of the original exception - as shown in the example below.

    class MyCustomException(Exception):
    pass
    
    a=10
    b=0 
    reuslt=None
    try:
        try:
            result=a/b
    
        except ZeroDivisionError as exp:
            print("ZeroDivisionError -- ",exp)
            raise MyCustomException("Zero Division ") from exp
    
    except MyCustomException as exp:
            print("MyException",exp)
            print(exp.__cause__)
    

    Output:

    ZeroDivisionError --  division by zero
    MyException Zero Division 
    division by zero
    

提交回复
热议问题