Python Advanced exception handling

Source: Internet
Author: User

Exception handling

When the code is running, bugs can occur for a variety of reasons, and the program will run out of trouble when it encounters a bug, while in daily production The program is not interrupted for long periods of time. Therefore, we need to do a good job of exception handling beforehand.

Abnormal

Print (x)  # General error will print a bunch of red errors

  

Exception Handling: for more reasonable handling of code errors that may occur

Try:    Print(x)exceptNameerror as Error:Print('Error:%s'% error)#Error: Name ' x ' is not definedElse:    Print('no exception execution code for else')Print('the other code')#will execute normally

In the example above, the exception processing format is summarized as follows:

"""     Try:  The code generally puts some code that we think might be wrong    except error type:   Here you can use the as+ variable name to receive error message        error after executing code    It is common to write error messages into the log file ...              Multiple except can be written to determine a variety of error types else: Normal code code executing code "" ",        regardless of                 exception or not 

Special: Finally, usually in the function to do exception handling, and return encountered will also be normal execution, you can do some finishing work, such as: Close open files.

deffunc ():Try: F= Open ('Except_file','W') F.write ('Test')        returnTrueexcept:        returnFalsefinally:        Print('This is finally') F.close ()Print(Func ())

Special: Universal Exception Type: Exception

Try :     Print (i) except Exception as Error:     Print (' error:%s'% error) """     Although there is a universal exception handling mechanism, but can predict the exception is to be handled separately    and separate exception handling content to be before the almighty " " "

Python Advanced exception handling

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.