Search code examples
pythontry-catchexcept

setting variables values to empty string in except clause in python


My problem is , i am setting some values to the multiple variables in try clause. what i want is , when one of the values of the variables is not available , it should be empty string in except clause but only for those variables which are not available. for your reference , here is my try clause...

  try:
        app_source_name_attr = json_data["APP_DATA"]['metadata']["app_source_name"]
        source_type_attr = json_data['APP_DATA']['metadata']['source_attributes_jsonb']['source_type']
        utm_source_attr = json_data['APP_DATA']['metadata']['source_attributes_jsonb']['utm_source']
        utm_medium_attr = json_data["APP_DATA"]['metadata']['source_attributes_jsonb']['utm_medium']
        utm_campaign_attr = json_data["APP_DATA"]["metadata"]["source_attributes_jsonb"]["utm_campaign"]
        utm_campaignid_attr = json_data["APP_DATA"]["metadata"]["source_attributes_jsonb"]["utm_campaignid"]

if values are not available , i want to pass empty string to that variable otherwise value should be passed which i set in try clause. so , how except clause should be ?

Thanks in advance


Solution

  • You can put empty string values before try clause, one variable for example:

    app_source_name_attr = ''
    try:
        app_source_name_attr = json_data["APP_DATA"]['metadata']["app_source_name"]
    except Exception:
        pass
    print(app_source_name_attr)  # will print empty string if exception occured inside try-except block