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

Python - exception

編輯:Python

Think aloud : Let's set a small goal first ,2 After hours, it is abnormal
Text begins

List of articles

  • Understanding anomalies
  • Abnormal writing
    • grammar
    • Quick experience
    • Capture exception
      • grammar
      • Experience
      • Catch multiple specified exceptions
      • Capture exception information description
      • Catch all exceptions
    • Anomalous else
    • Anomalous finally
  • expand
  • The transmission of exceptions
  • Custom exception

Understanding anomalies

When an error is detected , The interpreter can't continue , On the contrary, there are some wrong hints , That's what's called “ abnormal ”.
for example :

  • With r Open a nonexistent file in
open('test.txt','r')

  • Variables are defined before calling , If you call it first, an error will also be reported

Abnormal writing

grammar

try:
The code that could have an error
except:
If there is an exception to the execution of the code

Quick experience

demand : Try to r Mode open file , If the file doesn't exist , with w Mode on .

try:
open('test.txt','r')
except:
open('test.txt','w')

Capture exception

grammar

try:
The code that could have an error
except Exception types :
If the code executed by this exception type is caught

Experience

print(num) # NameError: name 'num' is not defined.
''' : The preceding is the error type ,: The following is the exception information .'''
try:
print(num)
except NameError:
print(' Erroneous ')
# Running results : Erroneous 

Catch multiple specified exceptions

When more than one exception is caught , The name of the exception type to be caught , Put it in except after , And use tuples to write .

try:
print(1/0)
except (NameError,ZeroDivisionError):
print(' Erroneous ')
# Running results : Erroneous 

Capture exception information description

try:
print(1/0)
except (NameError,ZeroDivisionError) as error:
print(error) # division by zero

Catch all exceptions

Exception Is the parent of all program exceptions .

try:
print(1/0)
except Exception as error:
print(error) # division by zero

Anomalous else

else Represents the code to execute if there are no exceptions

try:
print(1) # 1
except Exception as error:
print(error)
else:
print(' There is no exception else') # There is no exception else

Anomalous finally

finally Represents the code to be executed regardless of whether it is abnormal or not , For example, closing a file .

try:
f = open('test.txt','r')
except Exception as error:
f = open('test.txt','w')
else:
print(' No abnormal ') # Don't execute 
finally:
f.close()

expand

demand : Call other py File and run .

  1. There are two ways to enter a folder
  • win+r Input cmd → Open the run window
    cd + route
  • Open folder , Input cmd
  1. python + file name

The transmission of exceptions

demand :

  1. Try read-only mode test.txt file , If the file exists, there are read contents , If the file does not exist, you can extract the user .
  2. Reading content requires , Try looping through the content , During reading, if it is detected that the user accidentally terminates the program , be except Catch exceptions and prompt the user .

Code :

import time
try:
f = open('test.txt') # The default open mode is ‘r’
# Try looping through the content 
try:
while True:
con = f.readline()
# The read value has no content , Description has been read , The cycle should be rolled out 
if len(con) == 0:
break
print(con)
# Force to stop 1s The clock 
time.sleep(1)
except:
# ctrl + c To terminate the program , It's too fast , No time to press , Import time modular 
print(' The program was terminated unexpectedly ')
except:
print(' The file does not exist ')
finally:
f.close()
print(' The file is closed ')

effect :

Be careful : If you are pycharm Open in ,ctrl+c Maybe not , Refer to the expanded content above to open .

Custom exception

stay Python in , The syntax for throwing a custom exception is raise Exception class object .

effect : It is used to feed back the situation that does not meet the program logic to the user . Used to report errors .

demand : Insufficient password length , Abnormal Report ( User enters password , If the input length is insufficient 3 position , False report , That is, a custom exception is thrown , And catch the exception )

# 1. Custom exception classes 
class ShortInputError(Exception):
def __init__(self, length,min_len) -> None:
# The length of the password entered by the user 
self.length = length
# Minimum length required by the system 
self.min_len = min_len
# Set the description of the exception thrown 
def __str__(self) -> str:
return f' The length you entered is {
self.length}, No less than {
self.min_len}'
# 2. Throw custom exception 
def main():
try:
con = input(' Please input a password :')
if len(con) < 3:
raise ShortInputError(len(con),3)
# 3. Capture exception 
except Exception as result:
print(result)
else:
print(' The password has been entered ')
t = 0
t = 1
while t:
main()

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