Getting started with Python four: exceptions

Source: Internet
Author: User

First, abnormal

Exceptions are actions that are taken when an exception condition is triggered (interpreter or programmer)

Exceptions in C + + use try, throw, catch and other keywords, while Python uses try, raise, except, etc.

Second, standard anomalies

1. Summary:

Python exceptions are classes, where baseexception is the root class for all exceptions

Exception, Systemexit, Generatorexit, keyboardinterrupt are directly derived from baseexception

Other exception classes are either directly or exception derived from

2. Derivative diagram:

3, standard exception (according to Python core programming plus Python3 source code for extended modification):

    

Third, detection and processing anomalies

1, Try-except:
A. An except:

Try :    detected partial except  exception type:    Exception handling Section

The exception handling part is executed when the detected part appears with the specified exception type;
Ignores statements in except when no specified exception occurs

Example:

 1  try  :  2  f = open ( test.txt    )   Except   Filenotfounderror:  4  Span style= "color: #0000ff;" >print  ( this file is not exist!    )  #   6   When a file exists, it does not affect  

You can also ignore specific exceptions:

Try :    detected partial except  exception type:    Pass

This allows the processing to be ignored when a specific exception occurs:

1 Try : 2     f = open ('test.txt')3except  filenotfounderror: 4     Pass 5 6 # this way, when the file does not exist, it is ignored and the program continues to run

B. Exception parameters:
You can add: as parameter names after the exception section
You can use this parameter to preserve the cause of the error
Example:

1 Try:2f = open ('Test.txt')3 exceptFilenotfounderror as E:4     Print(str (e))5     Print(E.args)6 7 " "Output:8 [Errno 2] No such file or directory: ' Test1.txt '9 (2, ' No such file or directory ')Ten " " One  A #e is the exception parameter, preserving the cause of the exception error - #E is a tuple that consists of an error number and a string of error causes

C. Multiple except statements

Try :    Monitored section except  exception type 1:    handling 1except  exception type 2:    handling 2 ...

When an exception is detected, the appropriate exception handling section is executed
The rest of the except will not execute
Example:

1Exp = input ('Please input the math expression:')2 Try:3     Print(eval (exp))4 exceptZerodivisionerror as E:5     Print("0 can ' t be/or%")6 exceptTypeError as E:7     Print(e)8 9 " "Ten Input: 3 0 One output: 0 can ' t be/or% A Input: 3 & 1.5 - output: Unsupported operand type (s) for &: ' int ' and ' float ' - " "

D. Multiple exception types:

Try :    detected partial except  (Exception type 1, exception type 2, ...):    exception handling Section ...

Multiple exception types for the same treatment

E. Catch all Exceptions:
Because exception is the base class for all exceptions (except for a few special)
All can be used directly with exception as the exception type:

Try :    detected part except  Exception:    processing ...

Of course, if the error of the interpreter and the user forcibly interrupt are also captured, you can use Baseexception as the exception type

Note that when capturing all exceptions, it is best to take action instead of pass-off,

Ignore handling is generally only available for specific exceptions

Example:

F. Consolidated examples (excerpt from core Python programming):

1 defsafe_float (obj):2     """safe version of float (obj)"""3     Try:4retval =float (obj)5     except(ValueError, TypeError) as Diag:6         #valueerror: When incoming str etc7         #TypeError: When passing in {}, (), etc.8retval =Str (DIAG)9     returnretvalTen  One  A defMain (): -     """handles all the data processing""" -Log = open ('Cardlog.txt','W') the     #files used to keep the log -     Try: -Ccfile = open ('Carddata.txt','R') -     exceptIOError: +Log.write ('no Txns this month\n') - log.close () +         return A  atTxns =Ccfile.readlines () - ccfile.close () -Total = 0.0 -Log.write ('Account log:\n') -  -      forEachtxninchTxns: inresult =safe_float (EACHTXN) -         ifisinstance (result, float): toTotal + =result +Log.write ('data ... processed\n') -         Else: theLog.write ('ignored:%s'%result) *             #Ignore string, only for float processing $     Print('$%.2f (New Balance)'%Total )Panax Notoginseng log.close () -  the  + if __name__=='__main__': AMain ()

2. Else statement: Execute this Statement code when no exception is detected in the try Range

Try :    Monitored partial except  exception 1:    handling 1except  exception 2:    handling 2 ... Else :    processing

Only if exception 1, exception 2, ... is not detected before the Else statement is executed

Example:

3, finally statement: Regardless of whether the exception occurs, the code under the statement will be executed

A.try-except-finally:

Try :    detected partial except  exception:    processing ... finally :    statement block

Finally, the statement block will eventually execute

When an exception is generated within the try range, it jumps immediately to the finally statement

When the finally statement finishes executing, continue to raise the exception on one level

However, if the code in finally has an exception or is terminated due to return, break, continue, and so on, the original exception is not thrown

Example:

B.try-finally:

There is no except statement, and all purposes are not to handle exceptions,

This pattern is designed to maintain code execution, regardless of whether an exception occurs or not

Example (Credit card example close file):

Iv. triggering exceptions

An raise statement can be used to artificially throw an exception (similar to a throw in C + +)

Raise Someexception, Args, traceback

Application:

1 #only enter Q or enter is allowed2 Try:3Choice = input ('Please input [Enter]4ToContinue or[Q] to quit:')5     ifChoise not inch('Q','\ n'):6         RaiseIOError7 exceptIOError:8     Print('Just can input [Enter] or [Q]')

V. Assertions

Used to test an expression that triggers an exception if the return value is False

Try :     assert An expression except assertionerror:    handling

When an expression is false, the processing part is executed

Check the logic, documentation, conventions, etc. of the program before the product is released.
The assertion should be removed in the production environment
Example:

1 Try : 2 choice = input ('3continueor [Q] to quit:')  4assert in ('q'\ n ' ' 5 ...

Getting started with Python four: exceptions

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.