如果用户输入错误(不使用isinstance),如何捕获错误消息? [英] How do I catch the error message if the user gives wrong input (without using isinstance)?

查看:82
本文介绍了如果用户输入错误(不使用isinstance),如何捕获错误消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个代码,用于捕获我的错误消息,使用try和except(我想在不使用isinstance的情况下编写它)并且当输入不是整数时我收到错误消息。问题是,即使输入是有效整数,程序也会给我错误信息。请给我一些建议让它运行。我的代码如下:



 class酒店:
def __init __(self,room,catagory):
if room!= int:
raise TypeError()
self.room = room
self.catagory = catagory
self.catagories = {A:Elite,B :经济,C:常规}
self.rooms = [0,1,2,3,4,5]

def getRoom(self):
return self.room

def getCatagory(self):
return self.catagory
return self.catagories。 get(self.catagory)
def __str __(self):
返回%s和%s%(self.rooms [self.room],self.catagories.get(self.catagory))
尝试:
room1 =酒店(a,A)
room2 =酒店(1,A)
除外:
打印(有错误)







感谢您的帮助。



我尝试了什么:



我之前尝试过使用异常条款但是没有用。

解决方案

这种情况下,您可以更新代码以检查类型



 如果 类型(房间)   int:





打印出异常,试试



 import sys 



  except 
print 意外错误:,sys.exc_info()[ 0 ])





示例: CP_hotel | Pyfiddle [ ^ ]



错误处理 - 如何在Python中打印异常? - 堆栈溢出 [ ^ ]


I wrote a code to catch my error message using try and except (I want to write it without using isinstance) and I am getting the error message when the input is not an integer. The problem is, the program is giving me error message even if the input is valid integer. Please give me some suggestions to make it run. My code is given below:

class Hotel:
    def __init__(self,room,catagory):
        if room != int:
            raise TypeError ()
        self.room = room
        self.catagory = catagory
        self.catagories = {"A":"Elite","B":"Economy","C":"Regular"}
        self.rooms = ["0","1","2","3","4","5"]

    def getRoom(self):
        return self.room

    def getCatagory(self):
        return self.catagory
        return self.catagories.get(self.catagory)
    def __str__(self):
        return "%s and %s"%(self.rooms[self.room],self.catagories.get(self.catagory))
try:
    room1 = Hotel(a,"A")
    room2 = Hotel(1,"A")
except:
    print("there's an error")




I appreciate your help.

What I have tried:

I tried to use the exception clause before but that did not work.

解决方案

That case, you can update the code to check for type

if not type(room) is int:



to print out the exception, try

import sys


except:     
    print("Unexpected error:", sys.exc_info()[0])



Example: CP_hotel | Pyfiddle[^]

error handling - How to print an exception in Python? - Stack Overflow[^]


这篇关于如果用户输入错误(不使用isinstance),如何捕获错误消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆