Python basis: Exception Handling

How to handle exceptions

  Whatever happens, finally block statements will be executed, even if the previous try and excep block used in the return statement.
import sys
try:
    f = open('file.txt', 'r')
    #.... # some data processing
except OSError as err:
    print('OS error: {}'.format(err))
except:
    print('Unexpected error:', sys.exc_info()[0])
finally:
    f.close()
  If file.txt file does not exist, then finally statement throws the following exception
Traceback (most recent call last):
  File ".\errorhandle.py", line 24, in <module>
    f.close()
NameError: name 'f' is not defined
  Document literacy is best to use with open
import sys,os
inFile = 'file.txt'
if not os.path.exists(inFile):
    print(f'file {inFile} not exist')
    sys.exit()
with open(inFile, 'r') as fin:
    fin.read()

User-defined exceptions

class MyInputError (Exception):
     "" " Exception When there're errors in raised INPUT " "" 
    DEF  the __init__ (Self, value): # custom exception type of the initialization 
        self.value = value
     DEF  __str__ (Self): # Custom abnormal expressions of string type 
        return ( " {} INPUT iS invalid " .format (the repr (self.value))) 
    
the try :
     the raise MyInputError (. 1) # throws exception MyInputError 
the except MyInputError AS ERR:
     Print ( ' error: { } ' .format (ERR))

  Block of code results:

error: 1 is invalid input

 References:

  Geek Time "Python core technology and practical"

Guess you like

Origin www.cnblogs.com/xiaoguanqiu/p/10936595.html