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

Python exception handling

編輯:Python


List of articles

  • The difference between grammatical errors and exceptions
  • What are the common types of errors ?
  • What are the common anomalies ?
  • Capture exception
  • How to catch specific exceptions , grammar
  • else If no exception occurs, execute
  • finally It will be carried out anyway
  • Raising Exception Actively throw an exception

Python There are two types of errors in , Syntax errors and exceptions . An error is a problem in a program , Due to this problem , The program will stop executing . On the other hand , When something internal happens , Exception will be thrown , These events change the normal flow of the program

The difference between grammatical errors and exceptions

Grammar mistakes : seeing the name of a thing one thinks of its function , This error is caused by a syntax error in the code . It causes the program to terminate .
example :

# Initiation amount Variable
amount = 10000
if (amount > 2999)
print("hallo world")

Output :

abnormal : When the program is grammatically correct , But when the code causes an error , Exception will be thrown . This error does not stop the execution of the program , however , It will change the normal flow of the program .
example :

# initialization marks Variable
marks = 10000
# Use 0 Perform division
a = marks / 0
print(a)

Output :

In the example above , When we try to divide a number by 0 when , Reported divided by 0 Error of

Be careful : Exception is Python Base class for all exceptions in . Sure Here, Check the exception hierarchy .

What are the common types of errors ?

  • IOError: If you can't open the file
  • KeyboardInterrupt: When the user presses an unwanted key
  • ValueError: When the built-in function receives an incorrect parameter
  • EOFError: If you hit the end of the file without reading any data
  • ImportError: If the module cannot be found

What are the common anomalies ?

Exception name describe IndexError When retrieving the wrong index of the list .AssertionError This problem occurs when an assertion statement fails AttributeError When attribute assignment fails , This error will occur .ImportError When the imported module is not found , This will happen .KeyError When the dictionary key is not found , That's what happens .NameError When the variable is undefined , This error will occur .MemoryError When the program is out of memory , That's what happens .TypeError When functions and operations are applied with incorrect types , That's what happens .

Capture exception

try and except Statements are used to capture and process Python The abnormal . Statements that can throw exceptions are kept in try clause , The exception handling statement is written in except clause .

example : Let's try to access an array element whose index is out of bounds and handle the corresponding exception .

# Handling simple runtime errors Python Program
# Python 3
a = [1, 2, 3]
try:
print("Second element = %d" % (a[1]))
# Because there are only 3 Elements , This causes an error
print("Fourth element = %d" % (a[3]))
except:
print(" Index out of range ")

In the example above , Statements that may cause errors are placed in try sentence ( In this case, it is the second print sentence ) in . the second print Statement attempts to access a fourth element that does not exist in the list , This causes an exception . then , This exception is caused by except Statements capture .

How to catch specific exceptions , grammar

try There can be multiple statements except Clause , To specify handlers for different exceptions . Please note that , At most one handler will be executed . for example , We can add... To the above code IndexError. The general syntax for adding a particular exception is –

# Handling simple runtime errors Python Program
# Python 3
try:
# Statements that may throw exceptions
...
except IndexError:
# The statement that runs after an index exception occurs
...
except ValueError:
# A statement that runs after a value exception occurs
...

example : stay Python Catch a specific exception in

# Program to handle multiple errors with one
# except statement
# Python 3
def fun(a):
if a < 4:
# throws ZeroDivisionError for a = 3
b = a / (a - 3)
# throws NameError if a >= 4
print("Value of b = ", b)
try:
fun(3)
fun(5)
# note that braces () are necessary here for
# multiple exceptions
except ZeroDivisionError:
print(" It happened. ZeroDivisionError")
except NameError:
print(" It happened. NameError")

Output

If you will fun(3) Comment out , The output will be :

The reason why the above output is so , Because once python Try to visit b Value , It will happen NameError.

else If no exception occurs, execute

stay python in , You can also try-except Use... On the block else Clause , This clause must be in all except Clause exists after . Only when the try Clause does not throw an exception , The code will enter else block .

example : Try to use else Clause

# use try-except describe else Clause
# Python 3
# return a/b Function of
def AbyB(a, b):
try:
c = ((a + b) / (a - b))
except ZeroDivisionError:
print(" You can't divide by 0")
else:
print(c)
if __name__ == '__main__':
# Driver for testing the above functions
AbyB(2.0, 3.0)
AbyB(3.0, 3.0)

Output :

finally It will be carried out anyway

Python A keyword is provided finally, The keyword is always in try After execution . finally Always in try Execute after the block terminates normally , Or execute after some exceptions terminate .
grammar :

try:
# Code with possible exception ....
...
except:
# Capture exception
# Code executed after exception
...
else:
# If there is no exception, the code executed after
...
finally:
# Code that will execute anyway
...

example :

# Python The final demonstration of the program
# try No exception was thrown in the block
try:
k = 5 // 0 # trigger “ Divide by zero ” abnormal .
print(k)
# Handle zero division exception
except ZeroDivisionError:
print(" You can't divide by 0 ")
finally:
# Always execute this code
# Whether or not an exception is generated .
print(' This sentence will be executed no matter whether there is an exception ')

Output results :

Raising Exception Actively throw an exception

raise Statement allows the programmer to force a specific exception to occur .raise The only parameter in indicates the exception to be raised . This must be an exception instance or an exception class ( from Exception Derived classes ).

# Describe the program that threw the exception
try:
raise NameError("Hi there") # Throw out Error
except NameError:
print(" This is the exception I threw on my own initiative ")
raise # Determine if an exception was thrown

Output :


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