简体   繁体   English

如何在没有回溯的情况下进行异常处理?

[英]How do I do the exception without the traceback?

I have the function which you can see in the picture.我有你可以在图片中看到的功能。 How do I only return the last line only, when the exception is raised, without the other lines: traceback.., file"" etc.如何仅在引发异常时返回最后一行,而不返回其他行:traceback..、file"" 等。

def division(k, m):
    try:
        k / m
    except TypeError:
        raise ValueError ('hey') from None
    return k/ m

只想返回:ValueError:hey

If you want to hide the exception, use pass instead of raising another exception.如果要隐藏异常,请使用pass而不是引发另一个异常。

def division(k, m):
    try:
        return k/m
    except TypeError:
        pass

If the exception occurs, this will return None by default.如果发生异常,默认情况下将返回None You could replace pass with a different return statement that returns whatever you want to use instead.您可以用不同的return语句替换pass ,该语句返回您想要使用的任何内容。

You shouldn't do the division again outside the try , since that will just get the error that you wanted to hide again.你不应该在try之外再次进行除法,因为那只会得到你想再次隐藏的错误。

Just put就放

import sys
sys.tracebacklimit = 0

Somewhere in your code.在您的代码中的某处。 It will apply to all of your exception tracebacks though.不过,它将适用于您的所有异常回溯。 I personally can't think of why I would do it, but knock yourself out!我个人想不出为什么我会这样做,但把自己打倒!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何让python函数返回异常回溯或结果? - How do I have a python function return an exception traceback, or the result? 如何在python中引发异常之前切片回溯? - How do I slice a traceback before raising an exception in python? 如何在Python 3中使用traceback记录异常对象 - How do I log an exception object with traceback in Python 3 如何使用python日志框架使用回溯在警告或信息级别记录异常? - How do I log an exception at warning- or info-level with traceback using the python logging framework? 如何在没有回溯的异常中引发异常? - How to raise exception inside an exception without the traceback? 为什么我不能从已保存的异常中获得完整的回溯 - 我如何获得并保存完整的追踪? - Why don't I get a full traceback from a saved exception - and how do I get and save the full trace? 如何禁用向远程主机发送回溯? - How do I disable sending traceback to remote hosts? 我该如何处理此回溯名称错误? 这是我的第一个剧本 - How do i deal with this traceback name error? This is my first script 如何在python中恢复旧的回溯? (例如倒数第二) - How do I recover an older traceback in python? (eg second to last) 为什么我会收到此回溯错误? - Why do i get this traceback error?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM