Python Basics (19) _ Exception handling

Source: Internet
Author: User
Tags error handling

First, exception handling Errors and Exceptions:

1, the wrong kind:

1) Syntax error: This error, the syntax of the Python interpreter cannot be detected, must be corrected before the program executes

2) Logic error:

Example: res1=1/0, es2=1+ ' str '

2, Exception: Exception is the program run error signal, in Python, the error triggered by the following exceptions:

Traceback:y tracing the origin of the anomaly

Nameerror: Type of exception

Name ' AA ' is not defined: Exception value

3. Types of anomalies

Different exceptions in Python can be identified in different types (Python unifies classes and types, types as classes), different class objects identify different exceptions, an exception identifies an error

Common exceptions

Attributeerror attempts to access a tree that does not have an object, such as foo.x, but Foo does not have a property xioerror input/output exception; it is basically impossible to open the file Importerror the module or package cannot be introduced is basically a path problem or name error Indentationerror syntax error (subclass); The code is not aligned correctly indexerror the subscript index exceeds the sequence boundary, for example, when X has only three elements, it attempts to access the X[5]keyerror Attempting to access a key that does not exist in the dictionary Keyboardinterrupt CTRL + C is pressed Nameerror use a variable that has not been assigned to the object SyntaxError Python code is illegal, the code cannot compile (personally think this is a syntax error, Wrong) TypeError the incoming object type is not compliant with the requirements Unboundlocalerror attempts to access a local variable that is not yet set, basically because another global variable with the same name causes you to think that you are accessing it valueerror a value that the caller does not expect , even if the type of the value is correct

Other Exceptions:

Arithmeticerrorassertionerrorattributeerrorbaseexceptionbuffererrorbyteswarningdeprecationwarningenvironmenterroreoferror Exceptionfloatingpointerrorfuturewarninggeneratorexitimporterrorimportwarningindentationerrorindexerrorioerrorkeyboardint Erruptkeyerrorlookuperrormemoryerrornameerrornotimplementederroroserroroverflowerrorpendingdeprecationwarningreferenceerr Orruntimeerrorruntimewarningstandarderrorstopiterationsyntaxerrorsyntaxwarningsystemerrorsystemexittaberrortypeerrorunbou Ndlocalerrorunicodedecodeerrorunicodeencodeerrorunicodeerrorunicodetranslateerrorunicodewarninguserwarningvalueerrorwarni Ngzerodivisionerror
more Exceptions

Exception handling

1. Exception Handling Concept:

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 the capture succeeds, go to another processing branch, execute the logic you've customized for it, and the program won't crash, which is exception handling

2, 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.

3, how to do exception handling:

  Exceptions are caused by program errors, which are not related to exception handling and must be corrected before the program is run.

1. Use if judgment

Age=input (' >>: '). Strip () if Age.isdigit ():    int (age)

Summarize:

1.if-Judging exception handling can only be done for a piece of code, for the same type of error for different pieces of code you need to write the duplicate if to handle it.

2. Frequent writes in your program are not related to the program itself, and if it is related to exception handling, it is like patching around your code. Very poor readability.

3. This is to solve the anomaly, but there is a problem, so do not jump to the conclusion that if can not be used for exception handling. If you don't obey, do you think that your program doesn't have an exception before you learn try...except, and let it crash?

1 def Test ():2Print'Test Running')3Choice_dic={4     '1': Test5 }6  whileTrue:7Choice=input ('>>:'). Strip ()8     ifNot choice or choice notinchChoice_dic:Continue#这便是一种异常处理机制啊9 Choice_dic[choice] ()Ten  OneUntil you get to your service.
Exception Handling Examples

2. Python-specific syntax structure processing

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

1) Basic syntax

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>>valueerror:invalid literal for int () with base: ' Hello '

3) Exception classes can be multi-branched

Try:    print (' ===>run ')    num=input (' >>: ')    int (num)    d={' a ': 1}    print (' ==dic[' B ']=> ' , d[' B '])    1/0    l=[]    l[10000]    1+ ' 2 '    class Foo:        pass    foo.xexcept ValueError as E1:    Print (' ValueError: ', E1) except Keyerror as E2:    print (' Keyerror: ', E2) except Zerodivisionerror as E3:    print (' Zero: ', E3) except Indexerror as E4:    print (' Index: ', E4) except TypeError as E5:    print (' type: ', E5) except Attributeerror as E6:    print (' attr: ', E6)

4) Universal exception in Python's exception, there is a universal exception: Exception, he can catch arbitrary exceptions, namely:

Try:    print (' ===>run ')    num=input (' >>: ')    int (num)    d={' a ': 1}    print (' ==dic[' B ']=> ' , d[' B '])    1/0    l=[]    l[10000]    1+ ' 2 '    class Foo:        pass    foo.xElse: #没有异常时才会执行     
finally: #有没有异常都会执行print (' finally ')

5) Raise Active Trigger exception

Try:    raise TypeError (' type error ') except Exception as E:    print (e)

6) Custom Exceptions

Class Egonexception (baseexception):    def __init__ (self,msg):        self.msg=msg    def __str__ (self):        Return Self.msgtry:    raise Egonexception (' type error ') except Egonexception as E:    print (e)

7) Assertion

Students=[]students.append (' s1 ') students.append (' s2 ') assert  len (students) >  #断言条件成立才执行下面代码    Print (' hhhhh ')

Try: Except ways to compare the benefits of the IF way

Try: Except this exception handling mechanism is to replace if that way, allowing your program to enhance robustness and fault tolerance without sacrificing readability

Exception types are customized for each exception (Python unifies classes and types, type is a Class), and for the same exception, a except can be caught, an exception that can handle multiple pieces of code at the same time (without ' writing multiple if judgments ') reduces code and enhances readability

Use try: The way of except

1: Separate the error handling from the real work
2: Code easier to organize, clearer, complex tasks easier to implement;
3: No doubt, more secure, not due to some small negligence to make the program accidentally collapsed

When to use exception handling: 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 kind of stuff adds up, and it makes your code less readable .And exception handling this is not your 2b logic wipe the bottom of the paper, only in some abnormal unpredictable circumstances, should be added try...except, other logic errors should try to correct

Python Basics (19) _ 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.