Python Basics---exception handling in Python

Source: Internet
Author: User

Exception handling in Python

First, what is exception handling

The Python interpreter detects an error, triggering an exception (also allowing the programmer to trigger an exception himself)

Programmers write specific code that is specifically designed to catch this exception (this code is independent of the program logic and is related to exception handling)

If capture succeeds, go to another processing branch, execute the logic you have customized for it, and make the program not crash, which is exception handling.

Second, why to do exception handling

The Python parser goes to execute the program, detects an error, triggers an exception, the exception is triggered and is not processed, the program terminates at the current exception, and the code behind it does not run, who will use a software that is running with a sudden crash.

So you have to provide an exception handling mechanism to enhance the robustness and fault tolerance of your program.

Third, the syntax of exception handling

1. Basic syntax:

Python customizes a type for each exception, and then provides a specific syntax structure for exception handling

Grammar:

Try:     code block except exception type:    When an exception is detected in try, the logic for this position is executed
2. The exception class can only be used to handle the specified exception condition, and cannot be handled if a non-specified exception
# uncaught exception, program direct error  s1 = ' Hello '
Try: int (s1) except Indexerror as E: print E
3. Multi-Branch
S1 = ' Hello '
Try: int (s1) except Indexerror as E: print (e) except Keyerror as E: print (e) except ValueError as E: p Rint (e)
Basically not, which programmer will write a bunch of exceptions to deal with ...
4. Universal exception in Python's exception, there is a universal exception: Exception, he can catch arbitrary exceptions, namely:
1 s1 = ' Hello ' 2 try:3     int (s1) 4 except Exception as E:5     print (e)
5. Else in exception handling
s1 = ' Hello ' try:      int (s1) except Indexerror as E:     print (e) except Keyerror as E:     print (e) except Valueerr Or as E:     print (E) Else:     print (' Execute Me without exception ' in try code block) #只有在没有异常类型的情况下才能执行else后的代码 finally:     print (' No matter if it's abnormal or not, Will execute the module, usually for cleanup work)  #无论有没有异常都会执行在finally后面的代码
6. Create your own anomalies
Try:     raise TypeError (' type error ') except Exception as E:    print (e)
  Class Egonexception (baseexception):      def __init__ (self,msg):          self.msg=msg    def __str__ (self):         Return self.msg  try:     raise Egonexception (' type error ') except Egonexception as E:     print (e)
7. Assertions
1 # Assert condition   Assert 1 = = # determines that the condition satisfies this condition to execute the code otherwise it throws an exception. Assert 1 = = 2
8. Write in the last words
Attention:

Try...except should be used sparingly, because it is an exception-handling logic that you attach to your program, which is not related to your main work.
This adds a lot of stuff, which can cause your code to become less readable.

Try...except should be added only if some anomalies are unpredictable, and other logic errors should be corrected as much as possible.

Python Basics---exception handling 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.