Ben Franklin
Ben Franklin

Reputation: 27

raising an exception if a parameter is a string

I have seen other posts/videos in order to figure out how to solve this issue I am having but with no success. I am trying to raise an exception if the third parameter(p) is a string datatype but all my attempts in order to achieve this have not been successful and was looking for some help on what I am doing wrong.

class Friends(Ben):
    def __init__(self, frank, greg, p):
        Ben.__init__(self, frank, greg)
        self.p = p

        try:
            if p == str:
                raise TypeError("This is a string!")
        except:
            print("This not a string")

Upvotes: 0

Views: 1526

Answers (3)

Holomorphic Guy
Holomorphic Guy

Reputation: 86


class Ben:
    def __init__(self):
        pass

class Friends(Ben):
    def __init__(self,frank,greg,p):

        if isinstance(p, str):
            raise TypeError('Why are you giving me strings!')

        Ben.__init__(frank,greg)
        self.p = p

group = Friends('frank', 'greg', 'evil_string')

Output:


Traceback (most recent call last):
  File "C:\Users\StackOverflow\Desktop\temp.py", line 15, in <module>
    group = Friends('frank', 'greg', 'evil_string')
  File "C:\Users\StackOverflow\Desktop\temp.py", line 10, in __init__
    raise TypeError('Why are you giving me strings!')
TypeError: Why are you giving me strings!

Upvotes: 0

brentertainer
brentertainer

Reputation: 2188

There are a number of oddities in your piece of code; however, to address the issue of raising an Exception, you use raise to do that, as other answers indicate.

The try/except syntax is used to catch and handle exceptions when they occur. As an example, here is a reworked, standalone version of your code snippet that illustrates this.

class Friends:
    def __init__(self, frank, greg, p):
        if isinstance(p, str):
            raise TypeError(p, "This is a string!")
        self.p = p

try:
    friends = Friends('Frank', 'Greg', 'dubious_string')
except TypeError as e:
    print("Hey, I caught the error!")
    # print the exception
    print(e)
    # raise the exception again
    raise e

Output:

Hey, I caught the error!
('dubious_string', 'This is a string!')
Traceback (most recent call last):
  File "tmp.py", line 14, in <module>
    raise e
  File "tmp.py", line 10, in <module>
    friends = Friends('Frank', 'Greg', 'dubious_string')
  File "tmp.py", line 5, in __init__
    raise TypeError(p, "This is a string!")
TypeError: ('dubious_string', 'This is a string!')

Upvotes: 2

mm_
mm_

Reputation: 1735

I'm not sure what you are trying to do with the class, but I think this is what you are looking for:

#p = 10
p = "some string"
if type(p) == str:
    raise Exception("This is a string")

Upvotes: 0

Related Questions