< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

 

之前大多情况了下直接打印: 

 print(f"Caught an exception: {e}")  
复制代码
try:  
    # 尝试执行的代码块  
    risky_operation()  
except SomeSpecificException as e:  
    # 处理特定异常  
    print(f"Caught an exception: {e}")  
except AnotherSpecificException:  
    # 处理另一种特定异常  
    print("Caught another specific exception")  
except Exception as e:  
    # 处理所有其他异常  
    print(f"An error occurred: {e}")  
else:  
    # 如果没有异常,执行这个代码块  
    print("No exceptions occurred!")  
finally:  
    # 无论是否发生异常,这个代码块都会执行  
    print("Execution completed.")
复制代码

 

1. 使用 traceback 模块

traceback 模块提供了一些用于格式化和输出异常信息的工具。你可以使用 traceback.print_exc() 或 traceback.format_exc() 来获取详细的异常堆栈信息。

import traceback  
try:  
    # 故意制造一个异常  
    result = 10 / 0  
except Exception:  
    print("发生异常:")  
    traceback.print_exc()

格式化输出

你可以自定义输出格式,通过 str() 或 repr() 函数来控制输出的字符串形式。

复制代码
import traceback  

def pretty_print_exception(e):  
    error_message = f"发生异常: {str(e)}\n"  
    error_message += "详细信息:\n"  
    error_message += traceback.format_exc()  
    return error_message  

try:  
    # 故意制造一个异常  
    result = 10 / 0  
except Exception as e:  
    print(pretty_print_exception(e))
复制代码

 

 使用 f-string(Python 3.6 及以上)

通过 f-string 可以使打印信息更加简洁和可读:

 
try:  
    result = 10 / 0  
except ZeroDivisionError as e:  
    print(f"发生异常: {e} (类型: {type(e).__name__})")

 



posted on   lshan  阅读(59)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示
历史上的今天:
2019-07-24 常用书签
点击右上角即可分享
微信分享提示