Skip to main content
 首页 » 编程设计

Python之在 try-except-else 中捕获异常的简单方法

2025年05月04日15qq78292959

在Python中,我们可以使用as来捕获except语句中的异常实例。但是,似乎没有一种简单的方法可以在 try 之后的 else 语句中执行相同的操作。为了更清楚,请参阅下面的代码。

try: 
    raise Exception('Foo') 
except ValueError as valueError: 
    print(valueError) 
    print('I can capture the exception instance with "as" keyword') 
else:    # Cannot use "as" here 
    print('Some exception other than ValueError') 
    print('How can I capture the exception in order to, e.g. print its message?') 

有什么想法吗?

请您参考如下方法:

try: 
    raise Exception('Foo') 
except ValueError as valueError: 
    print(valueError) 
    print('I can capture the exception instance with "as" keyword') 
except Exception as e:   
    print(e) 
    print('Some exception other than ValueError') 
else: 
    print('no exception raised')