繁体   English   中英

如果代码错误,如何打印异常?

[英]How do I print an exception if error in code?

如果有功能,我会从网站上请求一些数据,但是当我遇到错误时,我想打印错误并重新启动代码。 但是我不知道确切的代码,可以请人帮我吗? 这是一个代码示例:

import time
input1 = input("Blabla: ")

def repeat():
    try:
        if input1 == "123":
            raise "Error: 123"
    except Exception as e:
        print(e)
        time.sleep(5) # Wait 5 seconds
        repeat() # Rerun code

repeat()

运行此代码时,出现错误“例外必须从BaseException派生”。 有人能帮我吗?

您不能只引发随机字符串作为例外。 如果要引发一般异常而不定义相关类型,只需引发Exception ,替换为:

raise "Error: 123"

与:

raise Exception("Error: 123")  # The "Error: " should probably be removed

或者,如果您可以使用更具体的错误,请这样做。 如果123因值错误而无效,请使用ValueError而不是Exception 如果有更具体的原因,请创建一个子类,以使其他人更容易捕获,例如(在模块的顶层):

class SpecialValueError(ValueError):
    pass

因此,您可以执行以下操作:

raise SpecialValueError("Error: 123")

而且人们可以专门捕获它,也可以通过平原except ValueError:except Exception:except Exception:来捕获它。

现在,您在打印错误对象的str时需要打印它的表示形式

尝试这个:

def repeat():
    try:
        if input1 == "123":
            raise Exception("Error: 123") # You need to use an Exception class
    except Exception as e:
        print(repr(e)) # Notice I added repr()
        time.sleep(5)
        repeat()

异常的表示与异常的字符串

串:

try: 
    raise Exception("Exception I am!") 
except Exception as e: 
    print(e) 
# Output: Exception I am!

表示:

try: 
    raise Exception("Exception I am!") 
except Exception as e: 
    print(repr(e)) 

# Output: Exception('Exception I am!')

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM