简体   繁体   中英

Python: multiple try/except blocks, print error if both exceptions fail?

I am trying to get my head around a try/except block. I have sqlite db with 2 tables that I want to load in different dataframes.

There are three possible outcomes, either table a or table b aren't there, or neither.

I am unclear how I would write that try/except block?

For example

try:
    df = pd.read_sql("select * from table_a", db)
    try:
        df2 = pd.read_sql("select * from table_b", db)
    except DatabaseError:
        print('no table b')
except DatabaseError:
    print('no table a')

How would I nest that to say that neither table a or b were found?

By un-nesting :)

try:
    df1 = pd.read_sql("select * from table_a", db)
except DatabaseError as exc:
    print('failed reading table a:', exc)
    df1 = None

try:
    df2 = pd.read_sql("select * from table_b", db)
except DatabaseError as exc:
    print('failed reading table b:', exc)
    df2 = None

if df1 is None and df2 is None:
    print('reading both tables failed')

Your existing code is probably the best way to handle this.

But if you want to change it to not distinguish between the two failures, you can just remove the inner try :

try:
    df = pd.read_sql("select * from table_a", db)
    df2 = pd.read_sql("select * from table_b", db)
except DatabaseError:
    print('either no table a, or no table b')

Or, if you want to detect both failures, just do them in sequence:

df = df2 = None
try:
    df = pd.read_sql("select * from table_a", db)
except DatabaseError:
    pass
try:
    df2 = pd.read_sql("select * from table_b", db)
except DatabaseError:
    pass
if not df and not df2:
    print('neither a nor b exists')

… and then you can add elif not df: and elif not df2: if you need those cases as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM