Click here to Skip to main content
15,887,350 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to write a program where the "except clause will run when the parameters are wrong but I am getting NameError when I am giving non-valid parameter. I wanted the print function to be run only when the parameters are correct but it is running even if the parameters are wrong and so I am getting error.
Can anyone suggest how can I get the output without getting the error?

My code is:

class Hotel:
    def __init__(self,room,catagory):
        if type(room) != int:
            raise TypeError()
        if type(catagory) != str:
            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.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")

except: 

    print("there's an error")


print (room1)


What I have tried:

I have tried to indent the print line inside and outside of the except condition but neither of the way worked.
Posted
Updated 17-Feb-19 16:29pm
Comments
Richard MacCutchan 18-Feb-19 4:22am    
Your Hotel class expects the first parameter to be an integer value. The variable a is not defined so it fails.

1 solution

if you look at the previous post:

How do I catch the error message if the user gives wrong input (without using isinstance)?[^], it explain how to display the detail error message with a demo.

the below line will give the error "NameError: name 'a' is not defined on line xx"
room1 = Hotel(a,"A")


the below line will give the error "TypeError: on line xx"
room1 = Hotel('a',"A")


As you can see, the first line is complaining about a is not a valid variable and it doesn't call the Hotel class

The second line, call the Hotel class and throw type error.

8. Errors and Exceptions — Python 3.7.2 documentation[^]
 
Share this answer
 
v2

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