Python3 try-except, raise and assert parsing Python3 try-except, raise and parsing assert

Python3 try-except, raise and resolve assert

I. Description

About exception catching try-except: when learning java would be a big advantage to catch the exception of education is relatively java c, the number of a few years also wrote some code, but it had always capture abnormal shape without his God, in which his own just let the program does not terminate the error occurred only when necessary termination.

About the initiative thrown raise: Some time ago to see the robot framework to determine the test case fails, is to monitor the use of their own initiative raise an exception thrown, this has been the initiative to throw the concept of exceptions.

About assert assert: Some time ago wrote a fuzzing tool, and then find a lot of downtime can cause problems after the development of the investigation, said the problem is due to newly added assertion; at the time of the assertion and not very clear, after they did not fix the problem further investigated.

In fact, the most important here is to say, after the discovery understand, try-except, raise and assert in fact have a significant relationship, it is necessary to record a record.

 

Second, the try-except exception caught

No exception catching a lot to say, the meaning of each language are similar writing format just a little different, we directly on the sample:

Copy the code
testTryExcept DEF (): 
    the try: 
        file_obj = Open ( 'myfile.txt') 
        str_var = file_obj.readline () 
        int_var = int (str_var.strip ()) 
    # If the detected anomaly is OSError class, the following process 
    # OSError as err indicate to the currently captured OSError an exception from the alias err; what name can be arbitrary 
    except OSError aS ERR: 
        Print (f "OS error: {ERR}") 
    # if not OSError detected is ValueError, the following processing 
    except ValueError: 
        Print (. "Could not the Data to Convert for AN Integer") 
    # If neither OSError nor ValueError but other abnormalities, the following processing 
    # exception as e represents an exception to the current captured from the alias e; what name It can be random 
    # If you do not need to print e, then the exception as e this part can be omitted 
    # myself, will not capture the specific type of exception that does not capture OSError as above and ValueError alone, so it only wrote edge except a would be finished
    the except Exception as e: 
        Print (F "Unexpected error: E {}") 
    # regardless of whether an exception occurs, finally part will be executed 
    # For the purposes of exception catching, finally part often can not, at least I have been not how to write 
    a finally: 
        file_obj.close ()
Copy the code

 

Third, take the initiative to throw an exception raise

In the top try-except we are passive and wait for abnormal capture ---- in fact the nature of these anomalies is passively waiting for the library functions raise the initiative thrown ---- we can take the initiative to raise the use of throw abnormal, that we can use to further raise thrown define yourself.

The benefits of the initiative to throw an exception, one can throw on the syntax is not considered abnormal but functionally we think is abnormal, and second, you can customize your own exception error statement more easily locate and troubleshoot anomalies.

Note that the initiative thrown exception is throwing an exception, it can still be captured by try-except.

Copy the code
# Custom exception classes must inherit Exception class, at least indirectly the Exception class inherits 
class PasswordException (Exception): 
    # define a variable password init method 
    DEF the __init __ (Self, password): 
        self.password password = 

    DEF __str __ (Self ): 
        return repr (self.password) 

DEF testRaise (): 
    # active thrown example 
    the try: 
        username = the iNPUT ( "Please the enter your username:") 
        # enter the username admin not throw an exception Exception 
        IF username =! "ADMIN": 
            the raise exception (f "Maybe your Privilege iS not enough: {username}") 
    # print that you can see our custom exception clause 
    the except exception AS E: 
        Print (f "{E}") 

    # active throw custom exception example 
    try:
        the INPUT = password ( "Please the Enter your password:") 
        # 123456 password is not the custom to throw the PasswordException abnormal 
        ! IF password = "123456": 
            The raise PasswordException (password) 
    # our custom abnormalities password variables, so we can directly select a variable print out 
    the except PasswordException AS E: 
        Print (F "PasswordException: e.password {}") 

IF the __name__ == "__main__": 
    testRaise ()
Copy the code

 

Fourth, the assertion assert

4.1 assert the nature of the discussion

See more official document: https://docs.python.org/3/reference/simple_stmts.html#the-assert-statement

assert the following use forms:

assert expression ["," expression]

If only shown by one expression that corresponds to the following:

if __debug__:
    if not expression: raise AssertionError

If the expression is shown by two, that is equivalent to the following:

if __debug__:
    if not expression1: raise AssertionError(expression2)

Which involves __debug__ and AssertionError follows:

__debug__: If the program runs without -O parameter, the True; otherwise it is False.

AssertionError: Exception exception class is a class inheritance, in which the source code builtins.py, as shown in FIG.

So, in essence, assert that raise a macro definition; a good expression of the immediately shown not to True, it throws an exception.

 

4.2 assert use

assert often used to check before operating parameters are used, if the check is not thrown directly by the early detection of an error, the error parameter is further avoid a significant back pass.

Note that due to the nature assert or raise, so you can use the same try-except capture, rather than that assertion error program will be terminated.

Copy the code
testAssert DEF (): 
    the try: 
        int_var = int (INPUT ( "Please Enter A Number positive:")) 
        # If the entered value is not greater than 0, the assertion failure, an exception is thrown 
        Assert int_var> 0 
    the except: 
        Print (F "Sorry, A positive Enter Number Please ") 
    Print (F" What you Enter IS: int_var {} ") 

IF the __name__ ==" __main__ ": 
    testAssert ()
Copy the code

 

reference:

https://www.runoob.com/python3/python3-errors-execptions.html

I. Description

About exception catching try-except: when learning java would be a big advantage to catch the exception of education is relatively java c, the number of a few years also wrote some code, but it had always capture abnormal shape without his God, in which his own just let the program does not terminate the error occurred only when necessary termination.

About the initiative thrown raise: Some time ago to see the robot framework to determine the test case fails, is to monitor the use of their own initiative raise an exception thrown, this has been the initiative to throw the concept of exceptions.

About assert assert: Some time ago wrote a fuzzing tool, and then find a lot of downtime can cause problems after the development of the investigation, said the problem is due to newly added assertion; at the time of the assertion and not very clear, after they did not fix the problem further investigated.

In fact, the most important here is to say, after the discovery understand, try-except, raise and assert in fact have a significant relationship, it is necessary to record a record.

 

Second, the try-except exception caught

No exception catching a lot to say, the meaning of each language are similar writing format just a little different, we directly on the sample:

Copy the code
testTryExcept DEF (): 
    the try: 
        file_obj = Open ( 'myfile.txt') 
        str_var = file_obj.readline () 
        int_var = int (str_var.strip ()) 
    # If the detected anomaly is OSError class, the following process 
    # OSError as err indicate to the currently captured OSError an exception from the alias err; what name can be arbitrary 
    except OSError aS ERR: 
        Print (f "OS error: {ERR}") 
    # if not OSError detected is ValueError, the following processing 
    except ValueError: 
        Print (. "Could not the Data to Convert for AN Integer") 
    # If neither OSError nor ValueError but other abnormalities, the following processing 
    # exception as e represents an exception to the current captured from the alias e; what name can be random 
    # If no print e, then this part of the Exception as e be omitted 
    # myself, will not capture the specific type of exception that does not capture OSError as above and ValueError alone, so it only wrote edge except a would be finished
    the except Exception as e: 
        Print (F "Unexpected error: E {}")
    # Regardless of whether an exception occurs, finally part will be executed 
    # For the purposes of exception catching, finally part often can not, at least I have been not how to write 
    a finally: 
        file_obj.close ()
Copy the code

 

Third, take the initiative to throw an exception raise

In the top try-except we are passive and wait for abnormal capture ---- in fact the nature of these anomalies is passively waiting for the library functions raise the initiative thrown ---- we can take the initiative to raise the use of throw abnormal, that we can use to further raise thrown define yourself.

The benefits of the initiative to throw an exception, one can throw on the syntax is not considered abnormal but functionally we think is abnormal, and second, you can customize your own exception error statement more easily locate and troubleshoot anomalies.

Note that the initiative thrown exception is throwing an exception, it can still be captured by try-except.

Copy the code
# Custom exception classes must inherit Exception class, at least indirectly the Exception class inherits 
class PasswordException (Exception): 
    # define a variable password init method 
    DEF the __init __ (Self, password): 
        self.password password = 

    DEF __str __ (Self ): 
        return repr (self.password) 

DEF testRaise (): 
    # active thrown example 
    the try: 
        username = the iNPUT ( "Please the enter your username:") 
        # enter the username admin not throw an exception Exception 
        IF username =! "ADMIN": 
            the raise exception (f "Maybe your Privilege iS not enough: {username}") 
    # print that you can see our custom exception clause 
    the except exception AS E: 
        Print (f "{E}") 

    # active throw custom exception example
    try:
        the INPUT = password ( "Please the Enter your password:") 
        # 123456 password is not the custom to throw the PasswordException abnormal 
        ! IF password = "123456": 
            The raise PasswordException (password) 
    # our custom abnormalities password variables, so we can directly select a variable print out 
    the except PasswordException AS E: 
        Print (F "PasswordException: e.password {}") 

IF the __name__ == "__main__": 
    testRaise ()
Copy the code

 

Fourth, the assertion assert

4.1 assert the nature of the discussion

See more official document: https://docs.python.org/3/reference/simple_stmts.html#the-assert-statement

assert the following use forms:

assert expression ["," expression]

If only shown by one expression that corresponds to the following:

if __debug__:
    if not expression: raise AssertionError

If the expression is shown by two, that is equivalent to the following:

if __debug__:
    if not expression1: raise AssertionError(expression2)

Which involves __debug__ and AssertionError follows:

__debug__: If the program runs without -O parameter, the True; otherwise it is False.

AssertionError: Exception exception class is a class inheritance, in which the source code builtins.py, as shown in FIG.

So, in essence, assert that raise a macro definition; a good expression of the immediately shown not to True, it throws an exception.

 

4.2 assert use

assert often used to check before operating parameters are used, if the check is not thrown directly by the early detection of an error, the error parameter is further avoid a significant back pass.

Note that due to the nature assert or raise, so you can use the same try-except capture, rather than that assertion error program will be terminated.

Copy the code
testAssert DEF (): 
    the try: 
        int_var = int (INPUT ( "Please Enter A Number positive:")) 
        # If the entered value is not greater than 0, the assertion failure, an exception is thrown 
        Assert int_var> 0 
    the except: 
        Print (F "Sorry, A positive Enter Number Please ") 
    Print (F" What you Enter IS: int_var {} ") 

IF the __name__ ==" __main__ ": 
    testAssert ()
Copy the code

 

reference:

https://www.runoob.com/python3/python3-errors-execptions.html

Guess you like

Origin www.cnblogs.com/jfdwd/p/11086689.html