PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, August 4, 2022

[FIXED] How do I get my main function to work while exceptions check the inputted variable?

 August 04, 2022     error-handling, exception, python, try-catch     No comments   

Issue

I managed to get my except functions working but that makes my main function not be able to work for some reason. I would really like to get my main function to work as it supposed to only accept letters and exception handle some possible errors encountered when inputting into the function.

def string_processor(string):  
    
    #The main function, 
    countA = 0
    if (string.isalpha()):
        for c in string:
            if c == "a":
                countA = countA + 1
            return (countA / len(string))
    
#finds any errors in the variable placed into the code
try:
    string_processor("aaaa")
except AttributeError:
    print("Please enter a string instead.")
except TypeError:
    print("Please input only 1 string.")
except NameError:
    print("This is not a string, please input a string")
else:
    print("String contained non-letters or unknown error occured")


For some reason, this code below is able to get the main function to work, but at the cost of only able to get Attribute errors and not the other specific errors such as TypeError and NameError.

def string_processor(string):  
    
    try:
        countA = 0
        if (string.isalpha()):
            for c in string:
                if c == "a":
                    countA = countA + 1
            return countA / len(string) 

#Exceptions
    except AttributeError:
        print("Please enter a string instead.")
    except TypeError:
        print("Please input only 1 string.")
    else:
        print("string contains non-letters or unknown error occured")
        
string_processor("1,","1")

Solution

The problem is that the else statement will be executed when the code have no exception.

Try to replace

else:
    print("string contains non-letters or unknown error occured")

to:

except Exception:
    print("String contained non-letters or unknown error occured")

or even better:

except Exception as e:
    print(e)

In this way, if you get an unexpected exception the program will print it



Answered By - Flavio Adamo
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing