@wanghuijiao
2021-06-04T07:58:12.000000Z
字数 5059
阅读 947
Python
SyntaxError: invalid syntax错误
import systry:# 先执行这段代码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 = 10if x > 5:raise Exception('x 不能大于 5。x 的值为: {}'.format(x))
>>> class MyError(Exception):def __init__(self, value):self.value = valuedef __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."""passclass InputError(Error):"""Exception raised for errors in the input.Attributes:expression -- input expression in which the error occurredmessage -- explanation of the error"""def __init__(self, expression, message):self.expression = expressionself.message = messageclass TransitionError(Error):"""Raised when an operation attempts a state transition that's notallowed.Attributes:previous -- state at beginning of transitionnext -- attempted new statemessage -- explanation of why the specific transition is not allowed"""def __init__(self, previous, next, message):self.previous = previousself.next = nextself.message = message
>>> def divide(x, y):try:result = x / yexcept ZeroDivisionError:print("division by zero!")else:print("result is", result)finally:print("executing finally clause")>>> divide(2, 1)result is 2.0executing finally clause>>> divide(2, 0)division by zero!executing finally clause>>> divide("2", "1")executing finally clauseTraceback (most recent call last):File "<stdin>", line 1, in ?File "<stdin>", line 3, in divideTypeError: 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 / ndef main():foo('0')# 断言失败则会报错:$ python err.pyTraceback (most recent call last):...AssertionError: n is zero!# 用 -O 关闭,关闭后,可以把所有的assert语句当成pass来看。$ python -O err.pyTraceback (most recent call last):...ZeroDivisionError: division by zero
import logginglogging.basicConfig(level=logging.INFO)s = '0'n = int(s)logging.info('n = %d' % n)print(10 / n)
# err.pyimport pdbs = '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 n0(Pdb) cTraceback (most recent call last):File "err.py", line 7, in <module>print(10 / n)ZeroDivisionError: division by zero