程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python learning 13 (exception)

編輯:Python

         In practice , The situation we encounter can't be perfect . such as ︰ A module you wrote , User input may not meet your requirements ; Your program is going to open a file , This file may not exist or it may not be in the right format ; You're going to read data from the database , The data may be empty ; Our program is running again , But the memory or hard disk may be full, etc . The software program is running , It is very likely to encounter the problems just mentioned , We call it an exception .

Catalog

One 、 Nature of anomaly mechanism

Two 、try... One except structure

Two 、try... Multiple except structure

3、 ... and 、try...except...else structure

Four 、try...except..finally structure

5、 ... and 、with Context management

6、 ... and 、trackback modular

Write exception information to the log file  

7、 ... and 、 Custom exception classes


One 、 Nature of anomaly mechanism

         Exception refers to the abnormal phenomenon in the process of program operation , For example, user input error 、 Divisor is zero. 、 The file to be processed does not exist 、 Array subscript out of bounds, etc .
         Exception handling , It means that the program can still correctly execute the remaining programs in case of problems , The program execution will not be terminated due to exceptions .

        Python in , Introduced many classes to describe and handle exceptions , Called exception class . The exception class definition contains the information of this kind of exception and the methods to deal with the exception .

BaseException

The parent of all exceptions

KeyBoardInterruptExceptionNameError、ValueError、AttributeError wait SystemExitGeneratorExit

        Python Everything in is the object , Exceptions are also handled as objects . Treatment process ;

        1. Throw an exception ∶ When executing a method , If something unusual happens , Then this method generates an object representing the exception , Stop the current execution path , And submit the exception object to the interpreter .

        2. Capture exception : When the interpreter gets the exception , Look for the appropriate code to handle the exception .

Two 、try... One except structure

        try...except Is the most common exception handling structure .

try:
Monitored statement blocks that may throw exceptions
except BaseException [as e]:
Exception handling statement block 

        try Blocks contain code that may throw exceptions ,except Blocks are used to catch and handle exceptions that occur . When it comes to execution , If try No exception was thrown in the block , Then skip ecept Block continues to execute subsequent code ; When it comes to execution , If try An exception occurred in the block , Then skip try Subsequent code in block , Jump to the corresponding except Handle exception in block ; After handling the exception , Continue with subsequent code .

Two 、try... Multiple except structure

        try...except Structure can catch all exceptions , It's also common at work . however , From the perspective of classical theory , It is generally recommended to catch as many exceptions as possible ( In the order of subclass first and then parent ), And write the exception handling code . To avoid missing possible exceptions , You can add... At the end BaseException. The structure is as follows :

try:
Monitored 、 Statement blocks that may throw exceptions
except Exception1:
Handle Exception1 Statement block
except Exception2:
Handle Exception2 Statement block
...
except BaseException:
A statement block that handles exceptions that may be missing 

3、 ... and 、try...except...else structure

        try ...excep...else The structure adds “else block ”. If try No exception was thrown in the block , execute else block . If try An exception is thrown in a block , execute except block , Don't execute else block .

Four 、try...except..finally structure

        try...except...finally In structure ,finally The block is executed whether or not an exception occurs ; Usually used to release try Resources requested in block .

5、 ... and 、with Context management

        finally Blocks are executed whether or not an exception occurs , Usually we put code that releases resources . Actually , We can go through with Context management , It is more convenient to release resources .

with context_expr [ as var]:
with_body

        with Context management can automatically manage resources , stay with After the code block is executed, the scene or context before entering the code is automatically restored . Jump out of... For whatever reason with block , Whether there is any abnormality or not , Always ensure the normal release of resources . It greatly simplifies the work , In file operation 、 Network communication related occasions are very common .

6、 ... and 、trackback modular

import traceback
try:
Code block
except:
traceback.print_exc() # Print trackback It's abnormal 

Write exception information to the log file  

import traceback
try:
print(1/0)
except:
with open( route ,'a') as f:
traceback.print_exc(file=f)

7、 ... and 、 Custom exception classes

         Program development , Sometimes we also need to define exception classes for ourselves . White defined exception classes are generally run-time exceptions , Usually inherited Exception Or its subclasses . Naming is generally based on Error、Exception For the suffix .

         Custom exception is defined by raise Statement actively throws .

class AgeError(Exception):
def __init__(self,errorInfo):
Exception.__init__(self)
self.errorInfo=errorInfo
def __str__(self):
return str(self.errorInfo)+", The age should be 1-150 Between "
############ Test code #############
if __name__=="__main__":
# Prevent others from running test files when calling your code , The test code only runs when this file is opened
age=int(input(" Please enter an age :"))
if age<1 or age>150:
raise AgeError(age)
else:
print(" Correct age :",age)
'''
Input 200 when :
Please enter an age :200
Traceback (most recent call last):
File " route ", line xx, in <module>
raise AgeError(age)
__main__.AgeError: 200, The age should be 1-150 Between
Input 7 when :
Please enter an age :7
Correct age : 7
'''

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved