Throw exception
#coding =utf-8
def exceptiontest (num):
If num<0:
Print "If Num<0"
Raise Exception ("Invalid num")
Else
Print num
If num = = 0:
Raise Zerodivisionerror ("Interger division or modulo by zero")
Print Exceptiontest (-43)
C:\python27\scripts>python task_test.py
If num<0
Traceback (most recent):
File "task_test.py", line +, in <module>
Print Exceptiontest (-43)
File "task_test.py", line 7, in Exceptiontest
Raise Exception ("Invalid num")
Exception:invalid num
#coding =utf-8
def exceptiontest (num):
If num<0:
Print "If Num<0"
Raise Exception ("Invalid num")
Else
Print num
If num = = 0:
Raise Zerodivisionerror ("Interger division or modulo by zero")
Return ""
Print Exceptiontest (4)
C:\python27\scripts>python task_test.py
4
#coding =utf-8
def exceptiontest (num):
If num<0:
Print "If Num<0"
Raise Exception ("Invalidnum")
Else
Print num
If num = = 0:
Raise Zerodivisionerror ("intergerdivision or modulo by zero")
Return ""
Printexceptiontest (0)
C:\python27\scripts>python task_test.py
0
Traceback (most recent):
File "task_test.py", line +, in <module>
Printexceptiontest (0)
File "task_test.py", line one, in Exceptiontest
Raisezerodivisionerror ("Interger division or modulo by zero")
Zerodivisionerror:interger division or modulo by zero
Custom exceptions
By creating a new Exception class, programs can create their own specific exceptions. Custom exceptions need to inherit the exception base class (Exception class), but can also inherit specific exception classes (such as RuntimeError), either directly or indirectly.
#coding =utf-8
Classneterror (RuntimeError):
def __init__ (Self,value): #重写默认的__ini__ () method
Self.value=value
#触发自定义的异常
Try
Raise Neterror ("bad hostname")
Exceptneterror,e:
Print "My exceptionoccurred,value:", E.value
C:\python27\scripts>python task_test.py
My exception Occurred,value:bad Hostna
#coding =utf-8
Classshortinputexception (Exception):
"A user-defined exception class."
def __init__ (self,length,atleast):
Exception.__init__ (self)
Self.length = length
Self.atleast = atleast
Try
s= raw_input (' Enter something--> ')
If Len (s) <3:
#如果输入的内容长度小于3, triggering an exception
Raise Shortinputexception (Len (s), 3)
Excepteoferror:
print ' \nwhy did you do a EOF on me? '
Exceptshortinputexception,x:
Print "shortinputexception:the Inputwas of length%d,\
Wasexcepting at least%d "% (x.length,x.atleast)
Else
Print "No exception was raised"
C:\python27\scripts>python task_test.py
Enter something-->234s
No exception was raised
C:\python27\scripts>python task_test.py
Enter something-->3e3
No exception was raised
C:\python27\scripts>python task_test.py
Enter something-->w
Shortinputexception:the input was of length 1, is excepting at least 3
C:\python27\scripts>python task_test.py
Enter something-->
Shortinputexception:the input was of length 0, is excepting at least 3
Exception throwing mechanism:
1. If an exception occurs at run time, the interpreter will find the appropriate processing statement (called handler).
2, if not found in the current function, it will pass the exception to the upper call function, to see if it can handle.
3. If the outermost (global "main") is not found, the interpreter exits and prints out the Traceback to allow the user to find the cause of the error.
Attention:
Although most errors cause exceptions, an exception does not necessarily represent an error, and sometimes they are just a warning, sometimes they may be a terminating signal, such as an exit loop, etc.
Standard exception Description
The standard exception set listed above, all exceptions are built-in. So they are already available before the script is started or when an interactive command-line prompt appears.
All standard/built-in exceptions are derived from the root exception. Currently, there are 3 exception subclasses that derive directly from Baseexception: Systemexit,keyboardinterrupt and exception. All other built-in exceptions are subclasses of exception.
Python2.5 begins, all exceptions are subclasses of the baseexception.
With introduction:
With is a new syntax introduced from Python2.5, which is a context management protocol designed to release the try,except and finally keywords and resource allocations from the flowchart for related
The code is stripped down, simplifying the try....except....finlally process. With is initialized by the __enter__ method, and then the __exit__ is done and the exception is handled. Therefore, objects that are processed using with must have both __enter__ () and __exit__ () methods. where the __enter__ () method goes into operation before the statement body (the block of code wrapped with the statement) executes, the __exit__ () method runs after the statement body executes and exits.
The WITH statement is useful for accessing resources, ensuring that the necessary "cleanup" operations are performed regardless of whether an exception occurs during use, freeing up resources such as automatic shutdown after file use, automatic acquisition and release of locks in threads, and so on.
The basic syntax format for the WITH statement is as follows
with expression [as Target]:
With_body
Parameter description:
Expression: is a need to execute the expressions;
Target: is a variable or tuple that stores the results returned by expression execution, optional arguments.
#coding =utf-8
With open ("D:\\a.txt", ' R ') as FP:
Print Fp.read ()
c:\python27\scripts>pythontask_test.py
Sdfsdfsdfsdf1
How the WITH statement works:
Immediately following the statement that follows with is evaluated, the __enter__ () method of the returned object is called, and the return value of the method is assigned to the variable following the AS keyword, and the __exit__ () method of the previous return object is called when all subsequent blocks of code are executed.
From the front we know that the key to the WITH statement is that the evaluated object must have both __enter__ () and __exit__ (), so we can customize the WITH statement to handle the exception by implementing both of these methods ourselves.
#coding =utf-8
Class opened (object):
def __init__ (self,filename):
Self.handle=open (filename)
Print "resource:%s"%filename
def __enter__ (self):
Print "[Enter%s]:allocateresource."%self.handle
Return self.handle# can be returned with different objects
Def__exit__ (Self,exc_type,exc_value,exc_trackback):
Print "[Exit%s]:freeresource."%self.handle
If Exc_trackback is None:
Print "[exit%s]:exited withoutexception.]%self.handle
Self.handle.close ()
Else
Print "[Exit%s]: Exited withexception raised."%self.handle
Return false# can be omitted, the default none is also considered False
withopened ("D:\\a.txt") as FP:
For line in Fp.readlines ():
Print Line
c:\python27\scripts>pythontask_test.py
Resource:d:\a.txt
[Enter<openfile ' d:\\a.txt ', mode ' r ' at 0x0000000002bc7150>]:allocate resource.
Sdfsdfsdfsdf1
[Exit<openfile ' d:\\a.txt ', mode ' r ' at 0x0000000002bc7150>]:free resource.
[Exit<openfile ' d:\\a.txt ', mode ' r ' at 0x0000000002bc7150>]:exited without exception.
Sample Code Description:
__enter__ () in opened returns a reference to itself, which can be assigned to the FP variable in the AS clause; the type of the return value can be set to a different type depending on the actual need, not necessarily the context Manager object itself.
The variable exc_trackback is detected in the __exit__ () method, if it is not none, indicating that an exception has occurred, that returning False indicates that the exception needs to be handled by external code logic, and that if no exception occurs, the default return value is None, which is also considered in a Boolean environment False, but because no exception occurred, __exit__ () Three parameters are none, the context management code can detect this situation, do normal processing. The 3 parameters of the __exit__ () method represent the type of exception, the value, and the stack information, respectively.
Name space
Random is a namespace
Import the Randint function in the Ramdom namespace
#encoding =utf-8
>>>from Random Import Randint
>>>print Randint (10,20)
18
Together to introduce two
>>>from Random Import Randint,choice
>>>print Randint (10,20)
11
>>>print choice ([1,2,3,4])
3
>>>
All functions are introduced directly with *, but the downside is that if a local custom function has the same name as a function in the namespace, the function in the namespace will be overwritten
>>>from Random Import *
>>>print Randint (10,20)
14
>>>print choice ([1,2,3,4])
4
>>>
Overlay examples:
#coding =utf-8
From random Import *
Def randint ():
Return 1
Print Randint (1,20)
c:\python27\scripts>pythontask_test.py
Traceback (most recent):
File "task_test.py", line 8, in<module>
Print Randint (1,20)
Typeerror:randint () takes no arguments (2 given)
Practice:
Generate a module a.py, which defines a variable c=100, defines a function def add (A, b) in the b.py by the import a and from a import * two methods to introduce the use of C variables and the Add function
a.py:
Import b
c=100
def add (A, B):
Return a+b
b.py:
Import a
Print A.C
Print A.add
c:\python27\scripts>pythontask_test.py
100
3
b.py:
#coding =utf-8
From a import *
Print C
Print Add (+)
c:\python27\scripts>pythontask_test.py
100
3
If there is an if __name__ = = ' __main__ ' in a py file: It is only executed when the file is run, it is referenced in the file and is not executed
a.py:
#encoding =utf-8
c=100
def add (A, B):
Return a+b
If __name__== ' __main__ ':
Print C
Print Add (10,20)
c:\python27\scripts>pythona.py
100
30
b.py:
#coding =utf-8
From a import *
Print C+add
c:\python27\scripts>pythontask_test.py
103
not shown a.py in if __name__== ' __main__ ': the code below
Import a in b.py, the code in a.py is executed once
Import a
Reload (a)
The code in a will be executed again after reload.
If import a is two times, execute the code in a only once
Import A
Import A
a.py:
#encoding =utf-8
c=100
def add (A, B):
Return a+b
Print "Import A, codes INA would run"
If __name__== ' __main__ ':
Print C
Print Add (10,20)
b.py:
#coding =utf-8
From a import *
c:\python27\scripts>pythontask_test.py
Import A,codes in a would run
B.py:import two times
#coding =utf-8
From a import *
From a import *
c:\python27\scripts>pythontask_test.py
Importa, codes in a would run
Execute only once
python-custom exceptions, with usage