简体   繁体   中英

Changing error types for user-defined function

Is there a scenario when you would catch an error and raise it as a different error. For example, if I have a function which reads a sheet from an excel file:

import pandas as pd
from xlrd import XLRDError

def readSheet(sheet, path):
    try:
        print("Reading {} sheet".format(sheet))
        return pd.read_excel(path, sheet_name=sheet)
    except XLRDError:
        raise ValueError("Sheet {0} not in {1}".format(sheet,path)))

My thought process would be that this raises a value error for the sheet variable in the function spreadsheet. Is it more appropriate to leave this error as XLRDError, ie

except XLRDError:
       raise XLRDError("message")

Perhaps a more general last thought would be is it idiomatic python to even perform this kind of exception handling? Instead, would it be better to let the function pd.read_excel handle and raise errors, for example:

def readSheet(sheet,path):
    #let any error handling be performed by the read_excel function.
    return pd.read_excel(path,sheet_name=sheet)

In general, yes, where the calling function knows more about what could go wrong than the called function .

For example, say you're reading from a Parquet archive with Pyspark. As it happens, if you attempt to read an empty folder, Pyspark will raise an AnalysisException , complaining that it can't infer the Parquet schema and that it must be specified manually.

If you know that this is the most likely cause, you can catch the error and raise a different, more descriptive one, or use the raise X from Y syntax to preserve the traceback.

The flip side is that you should be very sure that you have handled all cases in which such an exception will occur. Consider the following case:

def my_sum(a, b):
    return a + b

try:
    my_sum(1, 'one')

except TypeError:
    raise TypeError('Unsupported addition operation!')

Here, a TypeError that arises from trying to add two objects for which addition is undefined is raised and caught. However, the following code will also raise a TypeError , but the traceback will not make sense:

>>> my_sum(1)
TypeError: Unsupported addition operation!

This is a wholly different TypeError : one caused by the wrong number of arguments. Such erroneous exception handling can hinder debugging.

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