代码不会进入except子句进行错误处理

时间:2019-08-11 12:59:01

标签: try-except custom-error-handling

我是python的新手,正在尝试使一些代码工作。在代码中,我强制执行错误,并希望激活错误处理程序。

我试图用谷歌搜索这个问题,但是找不到解决方法...

#Main code
from Calculations import Errormessages as em
x = 'a'
try:
    y = 2/x
    print("y is:", y)

except em.error_str_input:
    print("This works (1)")

except error_0_input:
    print("This works (2)")

#From the Errormessages-file I import the following code:
class error(Exception):
    print("Wrong instruction given, please try again ...")
    pass
class error_str_input(error):
    print("... input numbers (not strings)!")
    pass
class error_0_input(error):
    print("... cannot divide by zero!")
    pass

我曾期望:

Wrong instruction given, please try again ...
... input numbers (not strings)!
This works (1)

但是导致以下错误消息:

File "//.../file.py", line 10, in <module>
    y = 2/x
TypeError: unsupported operand type(s) for /: 'int' and 'str'

1 个答案:

答案 0 :(得分:0)

此问题与try-except无关。

您正在尝试对int / str进行除法。

我认为您必须在除法时更改x值或使用ord(x)

例如=> y = 2/ord(x)

相关问题