Table of contents
1. You can use the try/except statement for exception capture.
3. The try statement works as follows;
2. The else clause will be executed when no exception occurs in the try clause.
8. Predefined Cleanup Behaviors
Nine, Python3 assert (assertion)
(3) The grammatical format is as follows:
(4) assert can also be followed by parameters:
(5) The following are assert usage examples:
(3) It is a good practice to use the with keyword when dealing with file objects.
(4) We can look at the following code examples:
1. Do not use with or try...except...finally
2. Next, we can use try...except...finally to improve the code:
4. We can check whether the file is closed after executing the with keyword:
5. The implementation principle of the with statement is based on the context manager.
1. Brief introduction
There are two types of errors in Python that are easily recognizable: syntax errors and exceptions.
Python assert (assertion) is used to judge an expression and trigger an exception when the expression condition is false.
Two, grammatical errors
Python grammatical errors or parsing errors are often encountered by beginners, as shown in the following example
>>> while True print('Hello world')
File "<stdin>", line 1, in ?
while True print('Hello world')
^
SyntaxError: invalid syntax
In this example, the function print() is checked for an error because it is missing a colon : in front of it.
The parser points out the wrong line and marks a small arrow at the location of the first error found.
3. Abnormal
Even if the syntax of a Python program is correct, errors may occur when running it. Errors detected at runtime are called exceptions.
Most exceptions will not be handled by the program, and are displayed here in the form of error messages:
Example:
>>> 10 * (1/0) # 0 cannot be used as a divisor, triggering an exception
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ZeroDivisionError: division by zero
>>> 4 + spam* 3 # spam is not defined, an exception is triggered
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'spam' is not defined
>>> '2' + 2 # int cannot be combined with str Add, trigger exception
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
Exceptions occur in different types, which are all printed as part of the message: the types in the example are ZeroDivisionError, NameError and TypeError.
The front part of the error message shows the context where the exception occurred, and the specific information is displayed in the form of a call stack.
4. Exception handling
(一)try/except
1. You can use the try/except statement for exception capture.
2. In the following example, the user is allowed to input a legal integer, but the user is allowed to interrupt the program (using Control-C or the method provided by the operating system). User interrupted information will raise a KeyboardInterrupt exception.
while True:
try:
x = int(input("Please enter a number: "))
break
except ValueError:
print("Your input is not a number, please try again!")
3. The try statement works as follows;
(1) First, the try clause (the statement between the keyword try and the keyword except) is executed.
(2) If no exception occurs, ignore the except clause, and end after the try clause is executed.
(3) If an exception occurs during the execution of the try clause, the rest of the try clause will be ignored. If the exception type matches the name after except, then the corresponding except clause will be executed.
(4) If an exception does not match any except, then the exception will be passed to the upper try.
4. A try statement may contain multiple except clauses to handle different specific exceptions. At most one branch will be executed.
5. The handler will only handle exceptions in the corresponding try clause, not exceptions in other try handlers.
6. An except clause can handle multiple exceptions at the same time, and these exceptions will be placed in a parenthesis to become a tuple
Example:
except (RuntimeError, TypeError, NameError):
pass
The last except clause can omit the name of the exception, it will be used as a wildcard. You can use this method to print an error message and then throw the exception again.
import sys
try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except OSError as err:
print("OS error: {0}".format(err))
except ValueError:
print("Could not convert data to an integer.")
except:
print("Unexpected error:", sys.exc_info()[0])
raise
(2) try/except...else
1. The try/except statement also has an optional else clause. If this clause is used, it must be placed after all except clauses.
2. The else clause will be executed when no exception occurs in the try clause.
3. The following example judges whether the file can be opened in the try statement. If there is no abnormality when opening the file, execute the statement in the else part to read the file content:
for arg in sys.argv[1:]:
try:
f = open(arg, 'r')
except IOError:
print('cannot open', arg)
else:
print(arg, 'has', len(f.readlines()), 'lines')
f.close()
Using the else clause is better than putting all the statements in the try clause, so as to avoid some unexpected exceptions that cannot be caught by except.
Exception handling not only handles exceptions that occur directly in the try clause, but also handles exceptions thrown in functions called in the clause (even indirectly called functions). For example:
>>> def this_fails():
x = 1/0
>>> try:
this_fails()
except ZeroDivisionError as err:
print('Handling run-time error:', err)
Handling run-time error: int division or modulo by zero
(3) try-finally statement
1. The try-finally statement will execute the last code no matter whether an exception occurs or not.
2. The finally statement in the following example will be executed regardless of whether an exception occurs:
try:
runoob()
except AssertionError as error:
print(error)
else:
try:
with open('file.log') as file:
read_data = file.read()
except FileNotFoundError as fnf_error:
print(fnf_error)
finally:
print( 'This sentence will be executed regardless of whether an exception occurs.')
5. Throw an exception
Python uses the raise statement to raise a specified exception.
The syntax format of raise is as follows:
raise [Exception [, args [, traceback]]]
The following example triggers an exception if x is greater than 5:
x = 10
if x > 5:
raise Exception('x cannot be greater than 5. The value of x 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 cannot be greater than 5. The value of x is: {}'.format(x)) Exception: x cannot be greater than 5. The value of x is: 10
The only parameter to raise specifies the exception to be thrown. It must be an instance of an exception or an exception class (that is, a subclass of Exception).
If you just want to know if this threw an exception, and don't want to handle it, then a simple raise statement can raise it again.
>>> try:
raise NameError('HiThere') # 模拟一个异常。
except NameError:
print('An exception flew by!')
raise
An exception flew by!
Traceback (most recent call last):
File "<stdin>", line 2, in ?
NameError: HiThere
6. User-defined exceptions
You can have your own exceptions by creating a new exception class. The exception class inherits from the Exception class and can be inherited directly or indirectly, for example:
>>> class MyError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
>>> try:
raise MyError(2*2)
except MyError as e:
print('My exception occurred, value:', e.value)
My exception occurred, value: 4
>>> raise MyError('oops!')
Traceback (most recent call last):
File "<stdin>", line 1, in ?
__main__.MyError: 'oops!'
In this example, the default __init__() of class Exception is overridden.
When creating a module that has the potential to throw many different exceptions, a common practice is to create a base exception class for the package, and then create different subclasses for different error conditions 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 exception names end with "Error", just like the standard exception names.
7. Define Cleanup Behavior
The try statement has another optional clause, which defines the cleanup behavior to be performed no matter what the circumstances. For example:
>>> try:
... raise KeyboardInterrupt
... finally:
... print('Goodbye, world!')
...
Goodbye, world!
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
KeyboardInterrupt
In the above example, regardless of whether there is an exception in the try clause, the finally clause will be executed.
If an exception is thrown in the try clause (or in the except and else clauses), and there is no except to catch it, then the exception will be thrown after the finally clause is executed.
Here's a more complex example (except and finally clauses in the same try statement):
>>> def divide(x, y):
try:
result = x / y
except ZeroDivisionError:
print("division by zero!")
else:
print("result is", result)
finally:
print("executing finally clause")
>>> divide(2, 1)
result is 2.0
executing finally clause
>>> divide(2, 0)
division by zero!
executing finally clause
>>> divide("2", "1")
executing finally clause
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'
8. Predefined Cleanup Behaviors
Some objects define a standard cleanup behavior that will be performed once it is no longer needed, regardless of whether the system successfully uses it.
The following example shows an attempt to open a file and print the contents to the screen:
for line in open("myfile.txt"):
print(line, end="")
The problem with the above code is that when execution is complete, the file remains open and is not closed.
The keyword with statement can ensure that objects such as files will correctly execute his cleanup method after use:
with open("myfile.txt") as f:
for line in f:
print(line, end="")
After the above code is executed, even if something goes wrong during processing, the file f will always be closed.
Nine, Python3 assert (assertion)
(1) Python assert (assertion) is used to judge an expression and trigger an exception when the expression condition is false.
(2) Assertions can directly return an error when the conditions are not met when the program is running, without waiting for the program to crash after running. For example, our code can only run under the Linux system, so we can first judge whether the current system meets the conditions.
(3) The grammatical format is as follows:
assert expression
Equivalent to:
if not expression: raise AssertionError
(4) assert can also be followed by parameters:
assert expression [, arguments]
Equivalent to:
if not expression: raise AssertionError(arguments)
(5) The following are assert usage examples:
>>> assert True # If the condition is true, execute normally
>>> assert False # If the condition is false, an exception will be triggered
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError
>>> assert 1 ==1 # If the condition is true, execute normally
>>> assert 1==2 # If the condition is false, an exception will be triggered
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError
>>> assert 1==2, '1 is not equal to 2'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError: 1 is not equal to 2
>>>
(6) The following example judges whether the current system is Linux. If the conditions are not met, an exception will be triggered directly without executing the following code:
import sys
assert ('linux' in sys.platform), "This code can only be executed under Linux"
# The code to be executed next
10. Python with keyword
(1) The with statement in Python is used for exception handling, which encapsulates the try...except...finally coding paradigm, which improves the usability.
(2) The with statement makes the code clearer and more readable, and it simplifies the management of public resources such as file streams.
(3) It is a good practice to use the with keyword when dealing with file objects.
(4) We can look at the following code examples:
1. Do not use with or try...except...finally
file = open('./test_runoob.txt', 'w')
file.write('hello world !')
file.close()
If an exception occurs in the process of calling write in the above code, the close method will not be executed, so the resource will always be occupied by the program and cannot be released.
2. Next, we can use try...except...finally to improve the code:
file = open('./test_runoob.txt', 'w')
try:
file.write('hello world')
finally:
file.close()
In the above code, we try to capture the code where an exception may occur. When an exception occurs, the except code block is executed, and the finally code block is executed no matter what the situation is, so the file will be closed and no resources will be occupied due to execution exceptions.
3. Use the with keyword:
with open('./test_runoob.txt', 'w') as file:
file.write('hello world !')
Using the with keyword, the system will automatically call the f.close() method, and the function of with is equivalent to the try/finally statement.
4. We can check whether the file is closed after executing the with keyword:
>>> with open('./test_runoob.txt') as f:
... read_data = f.read()
>>> # Check if the file is closed
>>> f.closed
True
5. The implementation principle of the with statement is based on the context manager.
A context manager is a class that implements __enter__ and __exit__ methods.
Using the with statement ensures that the __exit__ method is called at the end of the nested block.
This concept is similar to the use of try...finally blocks.
Example:
with open('./test_runoob.txt', 'w') as my_file:
my_file.write('hello world!')
The above example writes hello world! to the ./test_runoob.txt file.