>>>classBad(Exception):#user-defined exception...pass...>>>defdoomed(): ...raiseBad()#raise an instance...>>>try: ... doomed() ...exceptBad:#catch class name...print"got Bad"... got Bad>>> 3.5 终止行为 (Termination Actions) Finally,trystatements can say "finally"-- that is...
...int(l[2]) ... except ValueError, IndexError: # Tocatchboth exceptions, right? ... pass ... Traceback (most recent call last): File"", line3, in IndexError:listindex out of range 这里的问题是except语句不接受以这种方式指定的异常列表。在Python2.x中,except Exception语句中变量e可用...
# catch all errors and log it try: do_work() except: # get detail from logging module logging.exception('Exception caught!') # get detail from sys.exc_info() method error_type, error_value, trace_back = sys.exc_info() print(error_value) raise 1. 2. 3. 4. 5. 6. 7. 8. 9....
正常的 os.system() 执行完后只会返回个执行状态值,返回的 0 表示执行成功,1 表示执行失败。 如...
这里的问题在于except语句并不接受以这种方式指定的异常列表。相反,在Python 2.x中,使用语法except Exception,e是将一个异常对象绑定到第二个可选参数(在这个例子中是e)上,以便在后面使用。所以,在上面这个例子中,IndexError这个异常并不是被except语句捕捉到的,而是被绑定到一个名叫IndexError的参数上时引发的。
def fetcher(obj, index): return obj[index] x = 'spam' try: fetcher(x,9) except IndexError: print('got exception') got exception 现在,当try代码块内程序执行触发异常时,python会自动跳至处理器(即except分句下面的代码块)去运行。 def fetcher(obj, index): return obj[index] x = 'spam' try...
defprint_object(some_object):# Check if the object is printable...try:printable=str(some_object)print(printable)exceptTypeError:print("unprintable object") If the object can be coerced to a string, do so and print it. If that attempt raises an exception, print our error string. Same idea...
importsysdefbar(i):ifi ==1:raiseKeyError(1)ifi ==2:raiseValueError(2)defgood(): exception =Nonetry: bar(int(sys.argv[1]))exceptKeyErrorase: exception = eprint('key error')exceptValueErrorase: exception = eprint('value error')print(exception) good() ...
处理异常的标准方法就是使用try...except语句。这一点其实比较类似于Java中的try...catch语句,事实上,大部分语言都有类似的捕捉异常的方法。 通常来说,可能产生异常的代码应该被try语句囊括进去,如果报异常的就会立即停止try语句中的剩余代码,并执行except语句中的代码。
print "catch exception!" ... raise! ! ! ! ! # 原样抛出异常,不会修改 traceback 信息. >>> test() catch exception! Traceback (most recent call last): raise Exception("error!") Exception: error! 如果需要,可⽤用 sys.exc_info() 获取调⽤用堆栈上的最后异常信息. >>> def test(): ...