Mar 23, 2009

Python 异常,Assert

Assert

assert <test>, <data> # The <data> part is optional
相当于
if __debug__:
    if not <test>:
    raise AssertionError(<data>)

Exception

Python 支持异常处理:try...except...[else...不出现异常时执行的][finally...永远执行的]。
抛出的异常必须是异常类的实例
raise Exception()

用户定义的异常类必须继承 Exception 类或其子类。except SomeError 语句可以拦截 SomeError 实例,以及 SomeError 子类的实例。
最简单的异常类定义:
class FuncError(Exception): pass

使用时
e = FuncError(arg1, arg2, ...)
raise e
或直接
raise FuncError(arg1, arg2, ...)
它可以接受任意参数,这些参数保存在 e.args,用于提示错误

except FuncError as e:
print e.args

sys.exc_info
exc_info() -> (type, value, traceback)
Return information about the most recent exception caught by an except
clause in the current stack frame or in an older stack frame.

try:
    <statements> # Run this main action first
except <name1>:
    <statements> # Run if name1 is raised during try block
except (name2, name3):
    <statements> # Run if any of these exceptions occur
except <name4> as <data>:
    <statements> # Run if name4 is raised, and get instance raised
except:
    <statements> # Run for all (other) exceptions raised
else:
    <statements> # Run if no exception was raised during try block
finally:
    <statements> # Always perform this block.

except: Catch all (or all other) exception types.
except name: Catch a specific exception only.
except name as value: Catch the listed exception and its instance.
except (name1, name2): Catch any of the listed exceptions.
except (name1, name2) as value: Catch any listed exception and its instance.
else: Run if no exceptions are raised.
finally: Always perform this block.

raise <instance> # Raise instance of class
raise <class> # Make and raise instance of class
raise # Reraise the most recent exception (Propagating Exceptions,把当前的exception向上传播)

所以一个通常的try except 样子如下
try:
    action()
except NameError:
    ... # Handle NameError
except IndexError:
    ... # Handle IndexError
except:
    ... # Handle all other exceptions
else:
    ... # Handle the no-exception case

class ArgError(Exception): pass
class FirstArgError(ArgError): pass
    
def f(x,y):
    if x < 0:
        raise FirstArgError("x=%f, Negative number is not accept"%x)
    if y < 0:
        raise ArgError("Argument error")
        
try:
    f(-1,-1)
except FirstArgError as e:
    print e.args
except ArgError as e:
    print e.args

例子:导入库的处理
try:
    from EasyDialogs import AskPassword
except ImportError: 
    getpass = default_getpass
else:
    getpass = AskPassword

0 comments: