@wanghuijiao
2021-06-04T15:58:12.000000Z
字数 5059
阅读 552
Python
SyntaxError: invalid syntax
错误
import sys
try:
# 先执行这段代码
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except (RuntimeError, TypeError, NameError):
pass # 发生异常时执行的代码
except:
# 打印错误信息,用 raise 把错误抛出
print("Unexpected error:", sys.exc_info()[0])
raise
for arg in sys.argv[1:]:
try:
# 先执行这里
f = open(arg, 'r')
except IOError:
# try 有IOError异常,执行这里
print('cannot open', arg)
else:
# try 没异常,执行这里
print(arg, 'has', len(f.readlines()), 'lines')
f.close()
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('这句话,无论异常是否发生都会执行。')
raise [Exception [, args [, traceback]]]
x = 10
if x > 5:
raise Exception('x 不能大于 5。x 的值为: {}'.format(x))
>>> 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!'
在这个例子中,类 Exception 默认的 init() 被覆盖。
当创建一个模块有可能抛出多种不同的异常时,一种通常的做法是为这个包建立一个基础异常类,然后基于这个基础类为不同的错误情况创建不同的子类:
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
>>> 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'
for line in open("myfile.txt"):
print(line, end="")
with open("myfile.txt") as f:
for line in f:
print(line, end="")
def foo(s):
n = int(s)
# assert的意思是,表达式n != 0应该是True,否则,根据程序运行的逻辑,后面的代码肯定会出错。
assert n != 0, 'n is zero!'
return 10 / n
def main():
foo('0')
# 断言失败则会报错:
$ python err.py
Traceback (most recent call last):
...
AssertionError: n is zero!
# 用 -O 关闭,关闭后,可以把所有的assert语句当成pass来看。
$ python -O err.py
Traceback (most recent call last):
...
ZeroDivisionError: division by zero
import logging
logging.basicConfig(level=logging.INFO)
s = '0'
n = int(s)
logging.info('n = %d' % n)
print(10 / n)
# err.py
import pdb
s = '0'
n = int(s)
pdb.set_trace() # 运行到这里会自动暂停
print(10 / n)
# 调试
$ python err.py
> /Users/michael/Github/learn-python3/samples/debug/err.py(7)<module>()
-> print(10 / n)
(Pdb) p n
0
(Pdb) c
Traceback (most recent call last):
File "err.py", line 7, in <module>
print(10 / n)
ZeroDivisionError: division by zero