[英]Printing out error messages in python
So for a point class I'm making I have this error class: 所以对于点类,我正在使我有这个错误类:
class Error(Exception):
def __init__(self, message):
self.message = message
I'm using this to raise an error and print out a message for certain errors. 我正在使用它引发错误并为某些错误打印出一条消息。 What I'm doing here is printing out an error message if either x or y (or both) are not float values:
如果x或y(或两者)都不是浮点值,我在这里正在打印一条错误消息:
def __init__(self, x, y):
if not isinstance(x, float):
raise Error("Parameter \"x\" illegal.")
self.x = x
if not isinstance(y, float):
raise Error ("Parameter \"y\" illegal.")
self.y = y
By raising and printing errors that way, the error messages I get look like this: 通过以这种方式引发和打印错误,我得到的错误消息如下所示:
********** Point
*** constructor
caught: Parameter "x" illegal.
caught: Parameter "y" illegal.
0
***
But the error message is actually supposed to look like this: 但是错误消息实际上应该看起来像这样:
********** Point
*** constructor
caught: Parameter "x" illegal.
caught: Parameter "y" illegal.
0 1
***
So why does the expected output print a 1 next to the 0? 那么,为什么预期输出在0旁边打印1? Other error messages also include:
其他错误消息还包括:
*** rotate
caught: Parameter "a" illegal.
0
***
When I want it to look like: 当我希望它看起来像:
*** rotate
caught: Parameter "a" illegal.
0 -1
***
So is there something I'm not printing out in my error message? 那我的错误消息中有没有我没有打印出来的东西吗? Here's the code that prints out the error message:
这是打印出错误消息的代码:
print '*** constructor'
try:
p0 = Point(1,1.0) # x illegal
except Error as e:
print 'caught:', e.message
try:
p0 = Point(1.0,'y') # y illegal
except Error as e:
print 'caught:', e.message
print Point(0.0,1.0)
Here's my str method: 这是我的str方法:
def __str__(self):
return str(int(round(self.x)))
Default x and y to None: 默认x和y为None:
x = None
y = None
Then in str method, 然后在str方法中
def __str__(self):
str_x = ""
if self.x is not None:
str_x = str(int(round(self.x)))
str_y = ""
if self.y is not None:
str_y = str(int(round(self.y)))
return "%s %s" % (str_x, str_y)
Why not use python's built-in raise? 为什么不使用python的内置提升?
It will terminate the program and show an error message, just like it came out of the interpreter. 它将终止程序并显示错误消息,就像它来自解释程序一样。
If you're picky about the class, define it like this: 如果您对这个类很挑剔,可以这样定义它:
class YourNameHere(Exception): pass
Whether you defined the class or not, raise it like this: 不管您是否定义了类,都可以像这样引发它:
raise ExampleError("Parameter \"x\" illegal.","Parameter \"y\" illegal.")
It will show the following output: 它将显示以下输出:
Traceback (most recent call last):
File "C:/testanswer.py", line 3, in <module>
raise ExampleError("Parameter \"x\" illegal.","Parameter \"y\" illegal.")
ExampleError: ('Parameter "x" illegal.', 'Parameter "y" illegal.')
For single answers, there is no need to put it in a tuple. 对于单个答案,无需将其放在元组中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.