Click here to Skip to main content
15,887,434 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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.
Posted
Updated 16-Feb-19 19:18pm

1 solution

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

Python
if not type(room) is int:


to print out the exception, try

import sys

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


Example: CP_hotel | Pyfiddle[^]

error handling - How to print an exception in Python? - Stack Overflow[^]
 
Share this answer
 
v4
Comments
Member 14141186 17-Feb-19 17:33pm    
I wrote:


if type (room) != int:
raise TypeError()

But still I am getting the error message only when I am giving the valid integer in room2.

I did not understand what do you mean by: except Exception. I mean it would be helpful if you clarify a little bit more.

Thank you.
Bryian Tan 17-Feb-19 21:12pm    
here is an example: CP_hotel | Pyfiddle[^]

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900