Errors and exceptions
1. Distinguish between errors and exceptions
Two types of errors (which must be corrected) : syntax errors (bad code, ill-formed or missing symbols) and logical errors (illogical) exceptions: signals that something has gone wrong while a program is running
2. Exception handling and precautions
Exception handling: the programmer goes out of his way to catch the exception. If it succeeds, it will run in another section of logic you define so that the program will not crash
Note: exception handling logic should be separate from the main logic of the program; No one would use software that crashed in the middle of a run, so we had to provide an exception handling mechanism to make our programs more robust and fault-tolerant
All kinds of abnormal
1. Common exceptions
An AttributeError attempts to access an attribute that an object does not have, such as test.a, but test does not have an IOError input/output exception; Basically, you can’t open the file ImportError and can’t import modules or packages; It’s basically a path problem or a name error IndentationError syntax error; Code that does not properly indent or align IndexError subindexes beyond sequence boundaries, such as when a has only three elements and attempts to access a[5] KeyError key exceptions, Attempting to access a key that does not exist in the dictionary KeyboardInterrupt Ctrl+C is pressed NameError using a variable that has not yet been assigned an object SyntaxError Python code is illegal, UnboundLocalError Attempts to access a local variable that has not yet been set, basically because there is another global variable with the same name. ValueError causes you to think you are accessing it, passing in a value that the caller does not expect, even if the value is of the correct type
2. Other exceptions
ArithmeticError AssertionError AttributeError BaseException BufferError BytesWarning DeprecationWarning EnvironmentError EOFError Exception FloatingPointError FutureWarning GeneratorExit ImportError ImportWarning IndentationError IndexError IOError KeyboardInterrupt KeyError LookupError MemoryError NameError NotImplementedError OSError OverflowError PendingDeprecationWarning ReferenceError RuntimeError RuntimeWarning StandardError StopIteration SyntaxError SyntaxWarning SystemError SystemExit TabError TypeError UnboundLocalError UnicodeDecodeError UnicodeEncodeError UnicodeError UnicodeTranslateError UnicodeWarning UserWarning ValueError Warning ZeroDivisionError
These exceptions are relatively rare, so it is not necessary to list all the aspects of the exception, too many can not remember, so you can find the solution to search for these rare exceptions
Exception handling
1
While True: cou = input(' please input your account: \n') if cou.isdigit(): Elif cou.isspace() {int(cou) break () {elif cou.isspace(); Print continue elIf len(cou)==0: print elif cou.isalpha(): print elif cou.isalpha() Print (' no letters in account, please retype ') else: print(' Invalid input, please retype ') 123456789101112131415Copy the code
Running results:
Disadvantages of the if judgment:The same error type of different code sections needs to write repeated IF to deal with, which is very redundant and very poor readability
2, try… Except… Exception handling
While True: try: # cou = input(' cou: \n') int(cou) cou2 = input(' cou2: \n') int(cou2) except ValueError as e: Print (e,' please retype ') except KeyError as e: Print (e,' please re-enter ') except IndexError as e: Print (e,' please retype ') else: print(' If there is no exception inside the try, else will be executed ') Print (' no matter with or without exception in the try, finally can perform ') break # are commonly used to make clear the memory operations, or jump out of the loop 123456789101112131415161718192021222324Copy the code
Running results:
3. Active anomalies
Name = 'ViewIn' try: raise TypeError(' TypeError 'Copy the code
Running results:
4, assertions
Print (" -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --, line1 ') assert 1 = = 1 print (" = = = = = = = = = = = = = = = = = = = = = = = = = = = line2 ') # if assert expression was established, continued to perform, Otherwise the program terminates # equivalent to if 1! = 2: raise AssertionError # raise an exception # 123456789Copy the code
Running results: