I. Errors and exceptions 1. Error
Syntax or logic errors before code is run
- Syntax error (this error, the syntax of the Python interpreter cannot be detected, it must be corrected before the program executes)
def Test: ^Syntaxerror:invalid Syntax
# syntax error demonstration def Test: Pass # syntax error demonstration class Foo Pass # syntax error demonstration Print (haha
Other syntax errors
#用户输入不完整 (e.g. null input) or illegal input (input not a number)
Num=input ("")
int (num)
Output
>>: Fsftraceback (most recent): "/USERS/HEXIN/PYCHARMPROJECTS/PY3/DAY9/1. PY" in <module> for'FSF'
2. Exception definitions
A problem occurred during program execution that prevented the program from executing
- Classification of exceptions:
The program encountered a logical or algorithmic error
Computer error during Operation: Insufficient memory or IO error
An exception is generated, an error is checked and the interpreter considers it to be an exception, throwing an exception
Exception handling, exception handling, intercepting exceptions, system ignoring or terminating program handling exceptions
3. Common exceptions
Attributeerror attempts to access properties that an object does not have, such as foo.x, but Foo has no attribute x
IOError input / output exception; Basically, the file cannot be opened
Importerror cannot introduce modules or packages; it is basically a path problem or a name error
Indentationerror syntax error (subclass); Code not aligned correctly
Indexerror Subscript index is out of sequence bounds, for example, when X has only three elements, but tries to access x[5]
Keyerror attempts to access keys that do not exist in the dictionary
Keyboardinterrupt Ctrl+c is pressed
Nameerror attempt to access a variable that is not declared
SyntaxError python code is illegal, code can not compile (personally think this is a syntax error, write wrong)
TypeError incoming object types are not compliant with the requirements
Unboundlocalerror attempts to access a local variable that has not yet been set, basically because another global variable with the same name causes you to think that you are accessing it
ValueError Pass in a value that is not expected by the caller, even if the value is of the correct type
Add:
Exception Name Description baseexception the base class of all exceptions Systemexit interpreter request exits Keyboardinterrupt user interrupts execution (usually input^b) Exception General error base class Stopiteration iterator no more values Generatorexit Generator (Generator) exception occurs to notify the base class that exits StandardError all built-in standard exceptions Arithme Ticerror base class for all numeric calculation errors Floatingpointerror floating-point calculation error Overflowerror numeric operation exceeds maximum limit zerodivisionerror except (or modulo) 0 (all data types) Asserti OnError Assertion Statement failed Attributeerror object does not have this property eoferror does not have built-in input, reached the EOF tag EnvironmentError operating system error base class IOError input/output operation failed OSError operating system error Windowserror system call failed Importerror Import module/object failed lookuperror Invalid data query in the base class Indexerror sequence does not have this index (index) in Keyerror mapping does not have this key Memoryerror memory overflow error (not fatal for Python interpreter) N Ameerror 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 general run-time error Wrong Notimplementederror method syntaxerror Python syntax error indentationerror indentation error taberror Tab and space mixed Systemerror general explanation System error TypeError Invalid operation ValueError passed in invalid parameter Unicodeerror Unicode-related error unicodedecodeerror Unicode decoding error Unicodeenc Odeerror Unicode encoding error unicodetranslateerror Unicode conversion error warning warning base class deprecationwarning warnings about deprecated features Futurewarn ING warns of changes in the construction of future semantics overflowwarning old warnings about auto-promotion to long pendingdeprecationwarning the warning that the feature will be discarded runtimewarning Warning of suspected runtime behavior (runtime behavior) syntaxwarning suspicious syntax warning userwarning user code generated warning
Ii. exception handling 1. Definition of exception handling
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. Meaning of exception handling
The Python parser executes 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 subsequent code does not run, so you must provide an exception handling mechanism to enhance the robustness and fault tolerance of your program.
3. How to perform exception handling
Num1=input ('>>:')#Enter a string to tryifnum1.isdigit (): Int (NUM1)#Our Orthodox program is here, and the rest belongs to the exception-handling category .elifnum1.isspace ():Print('Enter a space and execute my logic here.')elifLen (num1) = =0:Print('the input is empty, just execute my logic here.')Else: Print('other situations, execute my logic here.')#The second piece of code#num2=input (' >>: ') #输入一个字符串试试#Int (num2)#The third paragraph of code#num3=input (' >>: ') #输入一个字符串试试#Int (num3)
Question one:
Using the If method we only add exception handling for the first piece of code, and for the second piece of code you have to re-write a bunch of if,elif and so on.
And these if, with your code logic is not related to the poor readability
Question two:
The first code and the second piece of code are actually the same exception, all valueerror, the same error is supposed to be handled only once, and if, because of the conditions of the two if, this can only force you to re-write a new if to deal with the exception of the second section of the code
The third paragraph is the same.
Grammar:
Try :< statements > # Run other code except < exception type >:< statement > # If the ' name ' exception is thrown in the try section except < exception type > as < data >:< statement > # If the ' name ' exception is thrown, get additional data else:< statement > # If no exception occurs
Note:
Python2 and 3 deal with the syntax of the EXCEPT clause is a little different, need attention;
Python2
Try: print (1/0) except Zerodivisionerror, err: #, plus reason parameter name print (' Exception: ', err)
Python3
Try: print (1/0) except Zerodivisionerror as err: # as plus reason parameter name print (' Exception: ', err)
Cases
Try: FH= Open ("testfile","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 ()
Output
Content written to file succeeded
Note:
The exception class can only be used to handle the specified exception condition, and cannot be processed if a non-specified exception occurs. ( exceptions are caused by program errors, syntax errors are not related to exception handling and must be fixed before the program is run)
# exception not caught, program directly error 'hello'try: int (s1)except Indexerror as E: print E
Output
" /users/hexin/pycharmprojects/py3/day9/1.py ", line one print e ^in'print'
Try: Msg=input ('>>:') int (msg)#ValueError # #print (x) #NameError # # ## l=[1,2] ## L[10] #IndexError # #1+ ' asdfsadfasdf ' #TypeErrorexceptValueError as E:Print(e)exceptNameerror:Print('Nameerror')exceptKeyerror as E:Print(e)
>>for'gg'
In Python exceptions, there is a universal exception: Exception, he can catch arbitrary exceptions
' Hello ' Try : int (s1)except Exception as E: ' discard or perform other logic ' Print(e)
Output
for ' Hello '
The try-finally statement executes the final code regardless of whether an exception occurs.
S1 ='Hello'Try: Int (s1)exceptIndexerror as E:Print(e)exceptKeyerror as E:Print(e)exceptValueError as E:Print(e)#except Exception 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
for ' Hello ' The module is executed whether it is unusual or not, usually for cleanup work
- Raise active triggering exception
We can use the raise statement to trigger the exception ourselves
The raise syntax format is as follows:
Raise[Exception[,[, traceback] ]
The type of exception in the statement is an exception (for example, the Nameerror) parameter is an exception parameter value. This parameter is optional and if not provided, the exception parameter is "None".
The last parameter is optional (rarely used in practice) and, if present, is the tracking exception object.
Try : Raise TypeError (' type error ')except Exception as E: Print (e)
Output
Type error
class hexinexception (baseexception): def __init__ (self,msg): self.msg=msg def__str__(self): return self.msgtry: raise hexinexception (' Type Error ' )except hexinexception as E: print(e)
Output
Type error
"Abnormal handling of Python3"