>>> For I in range (10)
File "<stdin>", line 1
For I in range (10)
^
SyntaxError: invalid syntax
In the above sentence, an error is reported because the interpreter cannot be interpreted due to the lack of colon. This error is reported by the Python syntax analyzer and the File and row number of the error (File "<stdin>", line 1) are detected ), the error location is also marked by the up arrow ^ (which is missing after:), and the error type is displayed.
Another common error is logical errors. Logical errors may be caused by incomplete or invalid input, or may be generated or computed, or other logical problems.
When Python detects an error, the interpreter cannot continue to execute it. Therefore, a prompt message is thrown, that is, an exception.
Exception
Common exceptions listed in the following table
Exception description
NameError attempts to access a variable without declaration
ZeroDivisionError divisor 0
SyntaxError syntax error
The IndexError index is out of the serial range.
KeyError requests a dictionary keyword that does not exist.
IOError input/output error (for example, the file you want to read does not exist)
AttributeError attempts to access unknown object attributes
NameError
>>> Bar
Traceback (most recent call last ):
File "<stdin>", line 1, in <module>
NameError: name 'bar' is not defined
Although you do not need to declare the type before using the variable in Python, you also need to assign values to the variable before using it. A variable that is not assigned a value can no longer exist in Python. Because a variable is equivalent to a tag, it is meaningful to paste it to an object.
ZeroDivisionError
>>> 1/0
Traceback (most recent call last ):
File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
SyntaxError
>>> For I in range (10)
File "<stdin>", line 1
For I in range (10)
^
SyntaxError: invalid syntax
This error occurs when the Python code is compiled. When this sentence is compiled, the interpreter cannot convert the code into a Python bytecode and reports an error.
IndexError and KeyError
>>> A = [1, 2, 3]
>>> A [4]
Traceback (most recent call last ):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>> D = {"python": "itdiffer.com "}
>>> D ["java"]
Traceback (most recent call last ):
File "<stdin>", line 1, in <module>
KeyError: 'Java'
IOError
>>> F = open ("foo ")
Traceback (most recent call last ):
File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: 'foo'
AttributeError
>>> Class A (object): pass # Python 3: class A: pass
...
>>> A = ()
>>> A. foo
Traceback (most recent call last ):
File "<stdin>", line 1, in <module>
AttributeError: 'A 'object has no attribute 'foo'
Exception handling
#! /Usr/bin/env python
# Coding = UTF-8
While 1:
Print "this is a division program ."
C = raw_input ("input 'C' continue, otherwise logout :")
If c = 'C ':
A = raw_input ("first number :")
B = raw_input ("second number :")
Try:
Print float (a)/float (B)
Print "*************************"
Except t ZeroDivisionError:
Print "The second number can't be zero! "
Print "*************************"
Else:
Break
Try... Except
For the above programs, we only look at try and try T. If no exception occurs, the try T clause is ignored after the try statement is executed. If there is an exception in the try clause, other statements in this part are ignored and directly jump to the limit T part to execute the specified exception type and its clause.
There can also be no exception type After limit T, that is, no exception parameter. In this case, retry T is executed no matter what exceptions occur in the try part.
In the limit T clause, you can perform more operations based on exceptions or other needs. For example:
#! /Usr/bin/env python
# Coding = UTF-8
Class Calculator (object ):
Is_raise = True
Def calc (self, express ):
Try:
Return eval (express) # running expression
Except t ZeroDivisionError:
If self. is_raise:
Print "zero can not be division." # Python 3: "zero can not be division ."
Else:
Raise # throw exception information
Handle multiple exceptions
Python 2:
#! /Usr/bin/env python
# Coding = UTF-8
While 1:
Print "this is a division program ."
C = raw_input ("input 'C' continue, otherwise logout :")
If c = 'C ':
A = raw_input ("first number :")
B = raw_input ("second number :")
Try:
Print float (a)/float (B)
Print "*************************"
Except t ZeroDivisionError:
Print "The second number can't be zero! "
Print "*************************"
Failed T ValueError:
Print "please input number ."
Print "************************"
Else:
Break
Or
Except t (ZeroDivisionError, ValueError): # contains multiple exceptions.
Print "please input rightly ."
Print "********************"
Print exception, but the program is not interrupted
While 1:
Print "this is a division program ."
C = raw_input ("input 'C' continue, otherwise logout :")
If c = 'C ':
A = raw_input ("first number :")
B = raw_input ("second number :")
Try:
Print float (a)/float (B)
Print "*************************"
Except t (ZeroDivisionError, ValueError), e: # similar to java
Print e
Print "********************"
Else:
Break
Python 3:
While 1:
Print ("this is a division program .")
C = input ("input 'C' continue, otherwise logout :")
If c = 'C ':
A = input ("first number :")
B = input ("second number :")
Try:
Print (float (a)/float (B ))
Print ("*************************")
Except t (ZeroDivisionError, ValueError) as e:
Print (e)
Print ("********************")
Else:
Break
Else statement
>>> Try:
... Print "I am try" # Python 3: print ("I am try "),
... Handle t:
... Print "I am trying t"
... Else: # The else will not run when processing the volume t
... Print "I am else"
...
I am try
I am else
Else statement application. The loop ends only when the correct content is entered.
#! /Usr/bin/env python
# Coding = UTF-8
While 1:
Try:
X = raw_input ("the first number :")
Y = raw_input ("the second number :")
R = float (x)/float (y)
Print r
Except t Exception, e: # python3 is Exception as e:
Print e
Print "try again ."
Else:
Break
Finally statement
If finally exists, try or retry T will be executed in the end. Similar to java
>>> X = 10
>>> Try:
... X = 1/0
... Couldn't Exception, e: # Python 3: Couldn T Exception as e:
... Print e # Python 3: print (e)
... Finally:
... Print "del x" # Python 3: print (e)
... Del x
...
Integer division or modulo by zero
Del x
Assert
Assert is equivalent to Boolean true determination. When an exception occurs, the expression is false. When the program runs on a node, it determines what the value of a variable must be, or the object must have a certain attribute. Simply put, it determines what is inevitable. If not, throw an exception.
#! /Usr/bin/env python
# Coding = UTF-8
If _ name _ = "_ main __":
A = 8
Assert a <0
Print
Traceback (most recent call last ):
File "/Users/liuguoquan/Documents Ents/workspace/PythonDemo/main. py", line 6, in <module>
Assert a <0
AssertionError
This is the reference of assert. What is the best time to use assertions? Some articles have summarized:
If there is no special purpose, assertions should be used in the following situations:
Defensive programming
Program Logic detection during runtime
Contract check (such as pre-condition and post-condition)
Constants in the program
Check document