Pregunta

# phone num
    try:
        phone=soup.find("div", "phone-content")
        for a in phone:
            phone_result= str(a).get_text().strip().encode("utf-8")
        print "Phone information:", phone_result
    except ValueError:
        phone_result="Error"

My program stops when there is a uni-code error but i want to use try except to avoid terminating the program. how can i do it?

I get different types of errors. i want something which just doesnt terminate the loop no matter whatever the error. just i want to skip the part of the loop which has error

¿Fue útil?

Solución

By using

try:
    ...
except:
    ...

You could always catch every error in your try block attempt. The problem with THAT is that you'll catch even KeyboardInterrupt and SystemExit

However, it's better to catch Errors you're prepared to handle so that you don't hide bugs.

try:
    ...
except UnicodeError as e:
    handle(e)

At a minimum, you should at least be as specific as catching the StandardError.

Demonstrated using your code:

try:
    phone=soup.find("div", "phone-content")
    for a in phone:
        phone_result= str(a).get_text().strip().encode("utf-8")
    print "Phone information:", phone_result
except StandardError as e:
    phone_result="Error was {0}".format(e)

See the Exception Hierarchy to help you gauge the specificity of your error handling. http://docs.python.org/2/library/exceptions.html#exception-hierarchy

Otros consejos

I think you can try something like this first:

try:
    whatever()
except Exception as e:
    print e

Then you will get your desired(!) exception [if it already exists], and then change it to except somethingelse

Or you can go for custom exception which will look something like following, but you have raise it where necessary:

class ErrorWithCode(Exception):
    def __init__(self, code):
        self.code = code
    def __str__(self):
        return repr(self.code)
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top