如果参数是字符串,则会引发异常

时间:2019-07-20 03:53:20

标签: python

我看过其他文章/视频,以便弄清楚如何解决我遇到的问题,但没有成功。如果第三个参数(p)是字符串数据类型,我正在尝试引发一个异常,但是我为实现该目标而进行的所有尝试均未成功,并正在寻求有关我做错事情的帮助。

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")

3 个答案:

答案 0 :(得分:2)

您的代码片段中有很多奇怪之处;但是,要解决引发异常的问题,请使用raise来执行此操作,如其他答案所示。

try / except语法用于在异常发生时捕获和处理异常。例如,这是您的代码段的重新制作的独立版本,对此进行了说明。

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

输出:

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!')

答案 1 :(得分:0)

我不确定您要在课堂上做什么,但是我认为这是您要寻找的内容:

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

答案 2 :(得分:0)

    try
    {
        SmtpClient client = new SmtpClient("sg2nlvphout-v01.shr.prod.sin2.secureserver.net", 25);
        client.EnableSsl = false;
        client.DeliveryMethod = SmtpDeliveryMethod.Network;
        client.UseDefaultCredentials = false;
        client.Credentials = new NetworkCredential("email@domain.com", "password");
        MailMessage msgobj = new MailMessage();
        msgobj.To.Add(email);
        msgobj.From = new MailAddress("email@domain.com");
        msgobj.Subject = "Subject";
        msgobj.Body = body;
        AlternateView altView = AlternateView.CreateAlternateViewFromString(msgobj.Body, null, MediaTypeNames.Text.Html);

        msgobj.AlternateViews.Add(altView);

        client.Send(msgobj);
    }
    catch (Exception ex)
    {

    }

输出:


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')