author : Han Xinzi @ShowMeAI
Tutorial address :http://www.showmeai.tech/tuto...
This paper addresses :http://www.showmeai.tech/article-detail/87
Statement : copyright , For reprint, please contact the platform and the author and indicate the source
In the actual programming process , I often see some error messages , stay python There are also special ways to handle errors and exceptions , Ensure that the overall process is smooth .
Python Grammatical errors and exceptions in are easily recognized , We can also use try...except To deal with it .
Beginners often encounter Python Wrong syntax or parsing , The following code example
>>> while True print('Hello ShowMeAI')
File "<stdin>", line 1, in ?
while True print('Hello ShowMeAI')
^
SyntaxError: invalid syntax
In this case , function print() It was detected that there was a mistake , A colon is missing in front of it : .
The parser points out the wrong line , And marked a small arrow in the wrong place that was first found .
Even if Python The syntax of the program is correct , When it's running , There is also the possibility of mistakes . Errors detected during runtime are called exceptions .
Most exceptions are not handled by the program , All in the form of error messages ( The following codes can be found in On-line python3 Environmental Science Run in ):
for i in range(5,-5,-1):
print(5/i)
give the result as follows :
1.0
1.25
1.6666666666666667
2.5
5.0
Traceback (most recent call last):
File "<string>", line 4, in <module>
ZeroDivisionError: division by zero
Exceptions come in different types , These types are printed as part of the message : The types in the examples are ZeroDivisionError,NameError and TypeError.
The first part of the error message shows the context in which the exception occurred , And display the specific information in the form of call stack .
Exception catching can be used try/except sentence .
In the following example , Let the user enter a legal integer , But allow the user to interrupt the program ( Use Control-C Or the method provided by the operating system ). User interrupted information will trigger a KeyboardInterrupt abnormal .
while True:
try:
x = int(input(" Please enter a number : "))
break
except ValueError:
print(" You are not entering numbers , Please try typing... Again !")
try The statement works as follows ;
One try The statement may contain more than one except Clause , To handle different specific exceptions , Only one branch will be executed .
The handler will only target the corresponding try Exception in Clause , Not the others try Exception in handler for .
One except Clause can handle multiple exceptions at the same time , These exceptions will be placed in parentheses as a tuple , for example :
except (RuntimeError, TypeError, NameError):
pass
the last one except Clause to ignore the name of the exception , It will be used as a wildcard . You can use this method to print an error message , Then throw the exception again .
import sys
try:
f = open('ShowMeAI.txt')
s = f.readline()
i = int(s.strip())
except OSError as err:
print(" System error : {0}".format(err))
except ValueError:
print(" Cannot convert to integer ")
except:
print(" Unknown error :", sys.exc_info()[0])
raise
try/except There is also an optional else Clause , If you use this clause , Then it must be put on all except After Clause .
else Clause will be try Clause is executed when no exception occurs .
The following examples are in try Statement to determine whether the file can be opened , If the file is opened normally without exception, execute else Part of the sentence , Read file contents :
for arg in sys.argv[1:]:
try:
f = open(arg, 'r')
except IOError:
print(' Can't open file ', arg)
else:
print(arg, ' Yes ', len(f.readlines()), ' That's ok ')
f.close()
Use else Clause is better than putting all statements in try The clause is better , This can avoid some unexpected , and except An exception that can't be caught .
Exception handling doesn't just deal with those that happen directly in try Exception in clause , It can also handle functions invoked in clauses ( Even indirectly called functions ) The exception thrown in . for example :
>>> def this_fails():
x = 1/0
>>> try:
this_fails()
except ZeroDivisionError as err:
print(' There is an error :', err)
# There is an error : int division or modulo by zero
try-finally Statement will execute the last code whether or not an exception occurs .
In the following example finally Statement executes whether or not an exception occurs :
try:
runoob()
except AssertionError as error:
print(error)
else:
try:
with open('ShowMeAI.log') as file:
read_data = file.read()
except FileNotFoundError as fnf_error:
print(fnf_error)
finally:
print(' Whether or not an exception occurs , Will execute this sentence .')
Python Use raise Statement throws a specified exception .
raise The syntax is as follows :
raise [Exception [, args [, traceback]]]
The following example code if x Greater than 10 Trigger the exception :
x = 20
if x > 10:
raise Exception('x Not greater than 10.x The value of is : {}'.format(x))
Executing the above code will trigger an exception :
Traceback (most recent call last):
File "test.py", line 3, in <module>
raise Exception('x Not greater than 5.x The value of is : {}'.format(x))
Exception: x Not greater than 10.x The value of is : 20
raise The only parameter that specifies the exception to be thrown . It must be an exception instance or an exception class ( That is to say Exception Subclasses of ).
If you just want to know if this throws an exception , Don't want to deal with it , So a simple raise Statement can throw it out again .
>>> try:
raise NameError('NewError')
except NameError:
print('An exception!')
raise
An exception!
Traceback (most recent call last):
File "<stdin>", line 2, in ?
NameError: NewError
You can have your own exceptions by creating a new exception class . Exception classes inherit from Exception class , Can inherit directly , Or indirectly , for example :
>>> class NewError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
>>> try:
raise NewError(2*2)
except NewError as e:
print('New exception occurred, value:', e.value)
My exception occurred, value: 4
>>> raise NewError('oops!')
Traceback (most recent call last):
File "<stdin>", line 1, in ?
__main__.NewError: 'oops!'
In this case , class Exception default __init__() Be overwritten .
When it is possible to create a module to throw many different exceptions , One common approach is to create a base exception class for this package , Then create different subclasses for different error situations based on this base class :
class Error(Exception):
"""Base class for exceptions in this module."""
pass
class InputError(Error):
"""Exception raised for errors in the input.
Attributes:
expression -- input expression in which the error occurred
message -- explanation of the error
"""
def __init__(self, expression, message):
self.expression = expression
self.message = message
class TransitionError(Error):
"""Raised when an operation attempts a state transition that's not
allowed.
Attributes:
previous -- state at beginning of transition
next -- attempted new state
message -- explanation of why the specific transition is not allowed
"""
def __init__(self, previous, next, message):
self.previous = previous
self.next = next
self.message = message
Most of the names of exceptions are "Error" ending , It's the same as the standard exception naming .
try Statement has another optional clause , It defines the cleanup behavior that will be performed in any case . for example :
>>> try:
... raise KeyboardInterrupt
... finally:
... print('Goodbye, ShowMeAI!')
...
Goodbye, ShowMeAI!
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
KeyboardInterrupt
The above examples do not matter try Is there any exception in the clause ,finally Clause will execute .
If an exception is in try In Clause ( Or in except and else In Clause ) To be thrown out , And nothing except Stop it , So this exception will be in finally Clause is thrown after execution .
Here's a more complex example ( In the same try The sentence contains except and finally Clause ):
>>> def divide(x, y):
try:
result = x / y
except ZeroDivisionError:
print(" Divisor is 0!")
else:
print(" The result is ", result)
finally:
print(" End of division calculation ")
>>> divide(2, 1)
The result is 2.0
End of division calculation
>>> divide(2, 0)
Divisor is 0!
End of division calculation
>>> divide("2", "1")
End of division calculation
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 3, in divide
TypeError: unsupported operand type(s) for /: 'str' and 'str'
Some objects define standard cleanup behavior , Whether or not the system successfully uses it , Once you don't need it , Then the standard clean-up will be carried out .
This example shows trying to open a file , Then print the content to the screen :
for line in open("ShowMeAI.txt"):
print(line, end="")
The problem with the above code is , When the execution is finished , The file will remain open , Not shut down .
key word with Statement can ensure that objects such as files will execute their cleanup methods correctly after use :
with open("ShowMeAI.txt") as f:
for line in f:
print(line, end="")
After the above code is executed , Even if something goes wrong in the process , file f Always close .
Please click to B I'm looking at it from the website 【 Bilingual subtitles 】 edition
https://www.bilibili.com/vide...
The code for this tutorial series can be found in ShowMeAI Corresponding github Download , Can be local python Environment is running , Babies who can surf the Internet scientifically can also use google colab One click operation and interactive operation learning Oh !
This tutorial series covers Python The quick look-up table can be downloaded and obtained at the following address :