Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· openaiHugging Face Suzhen/CodeChat

i use try except to catch error in python, but the error has 2 error, and i only able to…

  1. User

    i use try except to catch error in python, but the error has 2 error, and i only able to catch the lastest one, how can catch the first error

  2. Assistant

    You can catch multiple errors using multiple except clauses:

    try:
        # code that may raise multiple errors
    except ErrorType1:
        # code to handle ErrorType1
    except ErrorType2:
        # code to handle ErrorType2
    

    For example, if you want to catch both TypeError and IndexError, you can do:

    try:
        some_list = [1, 2, 3]
        item = some_list[4] + "string"
    except TypeError:
        print("Error: cannot add int and string")
    except IndexError:
        print("Error: index out of range")
    

    In this case, if an error occurs due to the index being out of range, the program will jump to the IndexError block, and if an error occurs due to attempting to add an int and a string, the program will jump to the TypeError block.

  3. User

    my case is creating the object into the db table, and it violate the fk of its field, the first error is psycopg2.errors.ForeignKeyViolation, the second is sqlachemy integrity error. how able the catch the psycopg2.errors.ForeignKeyViolation error?

  4. Assistant

    You can catch the psycopg2.errors.ForeignKeyViolation error separately before catching the sqlalchemy.exc.IntegrityError, like this:

    import psycopg2.errors
    from sqlalchemy.exc import IntegrityError
    
    try:
        # code to create object and commit to database
    except psycopg2.errors.ForeignKeyViolation:
        print("Error: ForeignKeyViolation")
    except IntegrityError:
        print("Error: IntegrityError")
    

    This will catch the ForeignKeyViolation error from psycopg2 separately before catching the IntegrityError from sqlalchemy. You can then print an appropriate error message for each case or handle the errors differently depending on your needs.