Python Exception handling

Source: Internet
Author: User

First: What is an exception

An exception is an event that occurs during program execution and affects the normal execution of the program.

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 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

Standard Exceptions:

Baseexception the base class of all exceptions Systemexit interpreter requests to exit Keyboardinterrupt user interrupt Execution (typically input^C) Exception General error base class Stopiteration iterator no more values Generatorexit Generator (generator) exception occurred to notify Exit StandardError all built-in standard exception base  Class Arithmeticerror All numeric calculation error base class Floatingpointerror floating-point calculation error Overflowerror numeric operation exceeds maximum limit zerodivisionerror except (or modulo) 0 (All data types) Assertionerror Assertion Statement failed Attributeerror object does not have this property Eoferror no built-in input, the base class to reach the EOF tag EnvironmentError operating system error IOError input/output operation failed OSError operating system error Windowserror system call failed Importerror Import module/The object fails lookuperror the base class of the invalid data query Indexerror sequence does not have this index in the Keyerror Map (index) Memoryerror Memory overflow error (not fatal for Python interpreter) Nameerror not declared/Initialize Object (no property) unboundlocalerror Access uninitialized local variable referenceerror weak reference (Weak reference) attempts to access an object that has been garbage collected runtimeerror Generic run-time error Notimplementederror method syntaxerror Python syntax error indentationerror indentation error taberror Tab and space mixed with SYS Temerror General interpreter system error TypeError invalid operation valueerror incoming invalid parameter unicodeerror Unicode related error u                Nicodedecodeerror Unicode decoding error unicodeencodeerror Unicode encoding when error unicodetranslateerror Unicode conversion error warning The base class of the warning deprecationwarning about deprecated features futurewarning warnings about the future semantics of constructs will change overflowwarning old about automatic promotion to long Integer (lon g) Warning pendingdeprecationwarning about the feature will be discarded warning runtimewarning suspicious runtime behavior (runtime behavior) warning syntaxwarning suspicious language Warning Userwarning user code generation
Standard ExceptionsSecond: Error

Errors are generally divided into two types:

Syntax error: This error cannot continue to run down:

Eg:1. No alignment

2.python3 in print without parentheses

Wait a minute

Logic error: Eg:

RES=1+STR (2)
Third: Exception handling

It is written in preface: The exception is caused by the error of the program, the grammatical error is not related to exception handling, it must be corrected before the program is run .

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.

You can use the Try/except statement to catch an exception.

The try/except statement is used to detect errors in a try statement block, allowing the except statement to catch exception information and handle it.

If you do not want to end your program when an exception occurs, simply capture it in a try.

Grammar:

The following is a simple syntax for try....except...else :

Try :< statements >        # Run other code except < name >:< statement >        # if the ' name ' exception is thrown in the try section except < name >,< data >:< statement >        # if the ' name ' exception is thrown, get additional data

If an exception occurs when the statement after the try is executed, Python jumps back to the try and executes the first except clause that matches the exception, and the control flow passes through the entire try statement (unless a new exception is thrown when the exception is handled).
If an exception occurs in the statement after the try, but there is no matching except clause, the exception will be submitted to the upper try, or to the top of the program (This will end the program and print the default error message).
If no exception occurs when the TRY clause executes, Python executes the statement after the Else statement (if there is else), and then the control flow passes through the entire try statement.

Eg: basic syntax:

Try: FH= Open ("Test","W") Fh.write ("This is a test file for testing exceptions !")exceptIOError:Print "Error: Failed to find file or read file"Else:    Print "content written to file succeeded"fh.close ()

The exception class handles the specified exception (if not captured, direct error):

Try :     Print (e) except Nameerror as E:     Print  'e' is not defined

Multi-Branch exception

d={'a', 1}Try:    Print(d['b'])exceptNameerror as E:Print(e)exceptTypeError as E:Print(e) Output:'Set'Object is  notSubscriptable

Universal anomaly

d={'a', 1}Try:    Print(c)Print(d['b'])exceptException as E:Print(e) Output: Name'C'  is  notDefinedd={'a', 1}Try:    Print(d['b'])    Print(c)exceptException as E:Print(e) Output:'Set'Object is  notSubscriptable

Else and finally

S1 ='Hello'Try: Int (s1)exceptIndexerror as E:Print(e)exceptKeyerror as E:Print(e)exceptValueError as E:Print(e)exceptException as E:Print(e)Else:    Print('execute My code block without exception in try')finally:    Print('The module is executed whether it is unusual or not, usually for cleanup work')#Output Result:#invalid literal for int. () with base: ' Hello '#The module is executed whether it is unusual or not, usually for cleanup work

To provoke an anomaly, where there is an anomaly, where to stir the anomaly.

Try :     Raise Nameerror (' unassigned object ')except  nameerror as e:     Print (e)    output: An object that has not been assigned a value
IV: Custom Exceptions
classzzlexception (baseexception):def __init__(self,msg): Self.msg=msgdef __str__(self):returnself.msgTry:    RaiseZzlexception ('Error')exceptzzlexception as E:Print(e) Output: Error
V: Assertion
   an assert's exception parameter, in fact, adds string information after an assertion expression to explain the assertion and better know where the problem   is. assert 2==1   assert 3==3

Python 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.