1 try-except
For example, if we want to open a file that does not exist, it will report an error
f=open('no.txt','r') f.read() ''' --------------------------------------------------------------------------- FileNotFoundError Traceback (most recent call last) <ipython-input-54-2709fabe0da7> in <module> ----> 1 f=open('no.txt','r') 2 f.read() FileNotFoundError: [Errno 2] No such file or directory: 'no.txt' '''
We can implement it with try except
try: f=open('no.txt','r') print(f.read()) except FileNotFoundError as e: print(e) f=open('no.txt','w') f.write('new file') f.close() ''' [Errno 2] No such file or directory: 'no.txt' '''
However, if we use unmatched error in except, we will still report an error
try: f=open('no1.txt','r') print(f.read()) except KeyError as e: print(e) f=open('no1.txt','w') f.write('new file') f.close() ''' --------------------------------------------------------------------------- FileNotFoundError Traceback (most recent call last) <ipython-input-56-5e0e21b6da44> in <module> 1 try: ----> 2 f=open('no1.txt','r') 3 print(f.read()) 4 except KeyError as e: 5 print(e) FileNotFoundError: [Errno 2] No such file or directory: 'no1.txt' '''
The solution is to use the base class Error
try: f=open('no1.txt','r') print(f.read()) except BaseException as e: print(e) f=open('no1.txt','w') f.write('new file') f.close()
2. Exception handling of multiple except s
d = {"name": "f1", "age": 2} l = [1,2,3] try: v = d["gender"] l[3] = 4 except KeyError as e: print("key error for:", e) d["gender"] = "x" except IndexError as e: print("index error for:", e) l.append(4) print(d) print(l) ''' key error for: 'gender' {'name': 'f1', 'age': 2, 'gender': 'x'} [1, 2, 3] '''
But here's one thing to note: it doesn't handle dictionaries at the same time KeyError And list IndexError
Because when the program is executed sequentially, as long as an error is reported, the code after the error will be terminated and enter the error recovery Link. This recycling link is in the above case except Error handling.
In other words, the except statement can execute only one.
Therefore, in the above example, the list l is not append ed
3 try except else statement
Try except is the same as the previous one else No error is reported during processing.
l = [1,2,3] try: l[3] = 4 except IndexError as e: print(e) else: print("no error, now in else") print(l) ''' list assignment index out of range ''' #At this time, there are exceptions, so the statements in except are executed l = [1,2,3,-4] try: l[3] = 4 except IndexError as e: print(e) else: print("no error, now in else") print(l) ''' no error, now in else [1, 2, 3, 4] ''' #There is no exception at this time, so the statements in try and else are executed
4 try except finally statement
Try exception is the same as the previous one. The statements in finally will be executed whether there are exceptions or not
In some cases, there seems to be no difference between finally and not
No exceptions:
l = [1,2,3,-1] try: l[3] = 4 except IndexError as e: print(e) finally: print("reach finally") ''' reach finally '''
l = [1,2,3,-1] try: l[3] = 4 except IndexError as e: print(e) print("reach finally") ''' reach finally '''
Abnormal:
l = [1,2,3] try: l[3] = 4 except IndexError as e: print(e) print("reach finally") ''' list assignment index out of range reach finally '''
l = [1,2,3] try: l[3] = 4 except IndexError as e: print(e) finally: print("reach finally") ''' list assignment index out of range reach finally '''
So, what do you need for the finally statement?
Let's look at the following example:
l = [1,2,3] try: l[3] = 4 print("reach finally") ''' File "<ipython-input-71-5a32d8788477>", line 6 print("reach finally") ^ SyntaxError: invalid syntax ''' l = [1,2,3] try: l[3] = 4 finally: print("reach finally") ''' reach finally --------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-75-26ba6fe359fd> in <module> 1 l = [1,2,3] 2 try: ----> 3 l[3] = 4 4 finally: 5 print("reach finally") IndexError: list assignment index out of range '''
Although all errors are reported, after finally is added, the statements in finally are executed first, and then an error is reported
5 raise
Manual trigger exception
def no_negative(num): if num < 0: raise ValueError("I said no negative") return num print(no_negative(-1)) ''' Traceback (most recent call last): File "/lib/python3.8/asyncio/futures.py", line 178, in result raise self._exception File "/lib/python3.8/asyncio/tasks.py", line 280, in __step result = coro.send(None) File "/lib/python3.8/site-packages/pyodide/_base.py", line 419, in eval_code_async return await CodeRunner( File "/lib/python3.8/site-packages/pyodide/_base.py", line 276, in run_async res = eval(last_expr, self.globals, self.locals) File "<exec>", line 6, in <module> File "<exec>", line 3, in no_negative ValueError: I said no negative '''
Note: here, the error type after raise must be the exception error type name defined in python (see section 6)
6 python exception error name table
Exception name | describe |
---|---|
BaseException | Base class for all exceptions |
SystemExit | Interpreter requests exit |
KeyboardInterrupt | User interrupts execution (usually enter ^ C) |
Exception | Base class for general errors |
StopIteration | The iterator has no more values |
GeneratorExit | An exception occurred in the generator to notify it to exit |
StandardError | Base class for all built-in standard exceptions |
ArithmeticError | Base class for all numeric errors |
FloatingPointError | Floating point calculation error |
OverflowError | The numeric operation exceeds the maximum limit |
ZeroDivisionError | Divide (or modulo) zero (all data types) |
AssertionError | Assertion statement failed |
AttributeError | Object does not have this property |
EOFError | No built-in input, EOF flag reached |
EnvironmentError | Base class for operating system error |
IOError | Input / output operation failed |
OSError | Operating system error |
WindowsError | system call filed |
ImportError | Failed to import module / object |
LookupError | Base class for invalid data query |
IndexError | This index does not exist in the sequence |
KeyError | This key is not in the map |
MemoryError | Memory overflow error (not fatal for Python interpreter) |
NameError | Object not declared / initialized (no properties) |
UnboundLocalError | Accessing uninitialized local variables |
ReferenceError | A weak reference attempts to access an object that has been garbage collected |
RuntimeError | General runtime error |
NotImplementedError | Methods not yet implemented |
SyntaxError | Python syntax error |
IndentationError | Indent error |
TabError | Mixing tabs and spaces |
SystemError | General interpreter system error |
TypeError | Invalid operation for type |
ValueError | Invalid parameter passed in |
UnicodeError | Unicode related errors |
UnicodeDecodeError | Error in Unicode decoding |
UnicodeEncodeError | Error encoding Unicode |
UnicodeTranslateError | Error converting Unicode |
Warning | Warning base class |
DeprecationWarning | Warning about deprecated features |
FutureWarning | Warning about future semantic changes in constructs |
OverflowWarning | Old warning about automatically promoting to long |
PendingDeprecationWarning | Warning that features will be discarded |
RuntimeWarning | Warning of suspicious runtime behavior |
SyntaxWarning | Warning of suspicious syntax |
UserWarning | Warnings generated by user code |