Detailed explanation of exception capture in python

  • 2021-08-28 20:26:57
  • OfStack

Anomaly

Exception is a signal that an error occurs in the program. Once the program makes an error, it will throw an exception, and the operation of the program will be terminated.


#  Exception handling 3 Feature 
-  Trace information of exceptions 
-  Type of exception 
-  Content of exception 

The purpose of catching exceptions: In order to enhance the robustness of the program, even if there is an error in the process of running, do not terminate the program, but catch exceptions and handle them, and record the error information in the log.


#  Grammatical error SyntaxError
-  Treatment mode 1 Must be corrected before the program runs 

#  Logical error 
-  The conditions under which errors occur are predictable  --> if Judge 
-  The conditions under which errors occur are unpredictable  -->  Exception trapping  try

Originally, the program 1 ended as a whole once an exception occurred. After exception handling, when an exception occurred in the detected code block, the code after the exception occurred in the detected code block will not be executed, and instead, the except sub-code block matching the exception will be executed, and the rest of the code will run normally.

Exception trapping

When different types of exceptions may be triggered in the detected code block, for different types of exceptions:

If we want to use different logic processing, we need to use multi-branch except (similar to multi-branch elif, it matches from top to bottom in turn, and it will not match others after matching successfully once)


try:
  #  Code that may throw an exception 
   Subcode 1
   Subcode 2
   Subcode 3
except  Exception type 1 as e:	# as Syntax assigns the value of exception type to variable e So that we can print e You can know the cause of the mistake 
  pass
except  Exception type 2 as e:
  pass
...
else:
   If no exception occurs in the detected child code block, it will be executed else Subcode of 
finally:
   Whether or not an exception occurs in the detected sub-code block, it will be executed finally Subcode of 

  
# try Can't be with else Used alone 
# try  And  finally  Use it together, even if there is an exception, it will be executed first finally Next code block and then throw an exception 

If we want to handle multiple types of exceptions with one logic, we can put multiple exceptions into one tuple and match them with one except.


try:
   Detected code block 
except (NameError,IndexError,TypeError):
   Trigger NameError Or IndexError Or TypeError The processing logic corresponding to the 

If we want to catch all exceptions and handle them with one logic, Python provides a universal exception type Exception


try:
   Detected code block 
except NameError:
   Trigger NameError The processing logic corresponding to the 
except IndexError:
   Trigger IndexError The processing logic corresponding to the 
except Exception:
   Other types of anomaly series 1 Use the logic here to process 

When the syntax or logic rules of the Python interpreter are not complied with, the Python interpreter initiatively triggers various types of exceptions, while when the rules of the programmer are violated, the programmer needs to trigger exceptions explicitly, which uses the raise statement. After raise, it must be an exception class or an exception instance


class Student:
  def __init__(self,name,age):
    if not isinstance(name,str):
      raise TypeError('name must be str')
    if not isinstance(age,int):
      raise TypeError('age must be int')

    self.name=name
    self.age=age

stu1=Student(4573,18) # TypeError: name must be str
stu2=Student('egon','18') # TypeError: age must be int

When the built-in exception is not enough, we can customize the exception class by inheriting the built-in exception class


class PoolEmptyError(Exception): #  You can inherit Exception To define 1 A brand new exception 
  def __init__(self,value='The proxy source is exhausted'): #  You can customize the initialization method 
    super(PoolEmptyError,self).__init__()
    self.value=value

  def __str__(self): #  You can define this method to customize the format for printing outlier values when an exception is triggered 
    return '< %s >' %self.value


class NetworkIOError(IOError): #  It can also be extended on the basis of specific exceptions 1 Related exceptions 
  pass


raise PoolEmptyError # __main__.PoolEmptyError: < The proxy source is exhausted >
raise NetworkIOError(' Connection denied ') # __main__.NetworkIOError:  Connection denied 

Finally, Python also provides an assertion statement assert expression, which concludes that the expression expression holds, otherwise it triggers an exception AssertionError, which has the same semantics as raise-if-not, as follows


age='18'

#  If the expression isinstance(age,int) The return value is False An exception is triggered AssertionError
assert isinstance(age,int)

#  Equivalent to 
if not isinstance(age,int):
  raise AssertionError

After understanding the exception handling mechanism, in order to improve the fault tolerance and reliability of the program, readers may mistakenly think that try... except... should be added to the program as much as possible, which is over-consuming the readability of the program, because try... except is an extra logic you attach to the program, which has little to do with your main work. So don't use exception catching casually, only when exceptions are unpredictable when they occur, or as a last resort.

The above is the detailed explanation of python exception capture details, more information about python exception capture please pay attention to other related articles on this site!


Related articles: