简体   繁体   English

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

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

If have a function were I request some data from a website but when I get an error I want to print the error and restart my code. 如果有功能,我会从网站上请求一些数据,但是当我遇到错误时,我想打印错误并重新启动代码。 But I don't know the exact code, can please someone help me? 但是我不知道确切的代码,可以请人帮我吗? This is a code example: 这是一个代码示例:

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()

When I run this code I get the error 'exceptions must derive from BaseException'. 运行此代码时,出现错误“例外必须从BaseException派生”。 Can someone help me? 有人能帮我吗?

You can't just raise random strings as an exception. 您不能只引发随机字符串作为例外。 If you want to raise a general exception without defining a relevant type, just raise Exception , replacing: 如果要引发一般异常而不定义相关类型,只需引发Exception ,替换为:

raise "Error: 123"

with: 与:

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

Alternatively, if you can use a more specific error, do so. 或者,如果您可以使用更具体的错误,请这样做。 If 123 is invalid because the value is wrong, use ValueError instead of Exception . 如果123因值错误而无效,请使用ValueError而不是Exception If there is some more specific reason, make a subclass to make it easier for others to catch, eg (at top level in the module): 如果有更具体的原因,请创建一个子类,以使其他人更容易捕获,例如(在模块的顶层):

class SpecialValueError(ValueError):
    pass

so you can do: 因此,您可以执行以下操作:

raise SpecialValueError("Error: 123")

and people can catch it specifically, or via plain except ValueError: , except Exception: , etc. 而且人们可以专门捕获它,也可以通过平原except ValueError:except Exception:except Exception:来捕获它。

Right now you are printing the error object's str while you need to print it's representation 现在,您在打印错误对象的str时需要打印它的表示形式

Try this: 尝试这个:

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()

Exception's Representation vs Exception's String 异常的表示与异常的字符串

String: 串:

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

Representation: 表示:

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