Exception handling of python notes

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 namedescribe
BaseExceptionBase class for all exceptions
SystemExitInterpreter requests exit
KeyboardInterruptUser interrupts execution (usually enter ^ C)
ExceptionBase class for general errors
StopIterationThe iterator has no more values
GeneratorExitAn exception occurred in the generator to notify it to exit
StandardErrorBase class for all built-in standard exceptions
ArithmeticErrorBase class for all numeric errors
FloatingPointErrorFloating point calculation error
OverflowErrorThe numeric operation exceeds the maximum limit
ZeroDivisionErrorDivide (or modulo) zero (all data types)
AssertionErrorAssertion statement failed
AttributeErrorObject does not have this property
EOFErrorNo built-in input, EOF flag reached
EnvironmentErrorBase class for operating system error
IOErrorInput / output operation failed
OSErrorOperating system error
WindowsErrorsystem call filed
ImportErrorFailed to import module / object
LookupErrorBase class for invalid data query
IndexErrorThis index does not exist in the sequence
KeyErrorThis key is not in the map
MemoryErrorMemory overflow error (not fatal for Python interpreter)
NameErrorObject not declared / initialized (no properties)
UnboundLocalErrorAccessing uninitialized local variables
ReferenceErrorA weak reference attempts to access an object that has been garbage collected
RuntimeErrorGeneral runtime error
NotImplementedErrorMethods not yet implemented
SyntaxErrorPython syntax error
IndentationErrorIndent error
TabErrorMixing tabs and spaces
SystemErrorGeneral interpreter system error
TypeErrorInvalid operation for type
ValueErrorInvalid parameter passed in
UnicodeErrorUnicode related errors
UnicodeDecodeErrorError in Unicode decoding
UnicodeEncodeErrorError encoding Unicode
UnicodeTranslateErrorError converting Unicode
WarningWarning base class
DeprecationWarningWarning about deprecated features
FutureWarningWarning about future semantic changes in constructs
OverflowWarningOld warning about automatically promoting to long
PendingDeprecationWarningWarning that features will be discarded
RuntimeWarningWarning of suspicious runtime behavior
SyntaxWarningWarning of suspicious syntax
UserWarningWarnings generated by user code

  Reference: How to control exceptions try exception - learn Python interactively | don't bother Python (mofanpy.com)

Keywords: Python elementUI

Added by riddhi on Wed, 08 Dec 2021 09:10:47 +0200