Comparison of two methods of handling errors in Python

Source: Internet
Author: User

What I call the way to deal with errors is actually try:,except and raise .

First throws an instance,

Dictt={' A ': 1, ' B ': 2, ' C ': 3}try:    if dictt[' d ']>1:   #字典中没有 ' d '        print ("right!") Except Keyerror:print ("There is no ' d '")

The running result of the program:

There is no ' d '

Instead of raise, the result is:

Obviously, because the ' f ' does not exist, the if cannot be executed, causing the raise to execute

The difference between the two (Try:,except and raise):

The former, no matter what the conditions in the if, can be run, no error, and the latter, if the conditions to meet a certain standard, otherwise raise cannot run. Also, raise will interrupt the program, showing a red error, and the red hint is set in raise.

In a word, the use of raise is generally of practical significance. Typical usage: Defines a function that takes multiple arguments, one of which is the wrong type, and it is appropriate to use raise for error hints.

Example:

#实现两个整数的加法运算def Summ (ADD1,ADD2):    if (Type (ADD1)) ==type (1) and (type (ADD2)) ==type (1):        return (ADD1+ADD2)    else:        raise TypeError ("The parameters should be integers")   

Comparison of two methods of handling errors in Python

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.