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

[Python foundation] exception handling mechanism

編輯:Python

Exception handling mechanism

  • One 、 exception handling
  • Two 、 Exception handling mechanism
  • 3、 ... and 、 An exception

One 、 exception handling

1、 Wrong type
ERROR abnormal : System type error , The cause may be a system crash , Out of memory , It is recommended that the procedure be terminated
Exception abnormal : Represents an exception that the program can handle , Can capture and possibly recover . This kind of problem can be solved .

2、 Error alert
Possible errors :

AttributeError .lOError . ImportError . IndexError、SyntaxError、TypeError、ValueError、KeyError、NameError.

Common mistakes are as follows :

. IndentationError: The indentation error
. KeyboardInterrupt: Ctrl+C Pressed
. UnboundLocalError : There is a global variable with the same name

3、 give an example

1、print(a)
NameError Wrong name , No such parameter
2、print(10/0)
ZeroDivisionError: division by zero The divisor cannot be zero 0
3、with open('hello.txt') as f:
pass
FileNotFoundError file error , There is no such document

Two 、 Exception handling mechanism

try: Try to run the program
except:try Something went wrong with the running code ( There can be more than one )
else:try There is no problem running the program
finally: Code that will run in any case

give an example
execpt It is to select one from many

try: Try to run
a=1
print(b)
except NameError as name_error: If the name is wrong
print('name_error')
except KeyError as key_error: If the keyword is wrong
print('key_error')
except Exception as all_error: If there is a mistake, then
print('all_error')
finally: In the end, we will implement it uniformly
print(' end ')

3、 ... and 、 An exception

1、raise Throw an exception

age = int(input('age:'))
if 0<age<150:
print(age)
else:
# Throw an exception 
raise ValueError(" Age must be in 0~150 Between ")
# result 
Input 100
ValueError: Age must be in 0~150 Between

2、 Custom exception
Through custom exception

# Custom exceptions 
class AgeError(ValueError): Custom error module :AgeError, It belongs to ValueError class
pass
age = int(input('age:'))
if 0<age<150:
print(age)
else:
# Throw an exception 
raise AgeError(" Age must be in 0~150 Between ")
# result 
Input 1000
AgeError: Age must be in 0~150 Between
``

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