Java - overriding Object's toString() method, but I have to throw exceptions

后端 未结 6 1235
抹茶落季
抹茶落季 2020-12-20 17:53

I have run into an issue where I have to override Object\'s toString() method, but the original method doesn\'t throw any exceptions. However, I am using some generic code t

6条回答
  •  清歌不尽
    2020-12-20 18:31

    Judging by the exceptions, I take it this is the offending line which might throw?:

    Position> current = fList.first();
    

    If that's the case, you can handle that exception. I don't know precisely what fList is and I'm not familiar enough with Java to know if the compiler will be smart enough to know you've checked for it, but logically if the fList could be empty then I would check for that first:

    if (/* check for an empty or null fList */) {
        return "";
    }
    // the rest of your code
    

    If the compiler still doesn't like that, you can take the pretty much the same approach with another try/catch. Something like:

    try {
        // the rest of your code
    } catch (Exception e) {
        return "";
    }
    

    At that point the method really shouldn't be able to throw, since any exception would result in simply returning an empty string. So the header shouldn't need the exception types listed.

    As a matter of personal preference I would recommend doing something with the exception when it's caught. At least logging it somewhere, even as a debug log and not necessarily an error. A blanket ignore on all possible exceptions isn't often the best of ideas in the long run.

提交回复
热议问题