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

后端 未结 6 1234
抹茶落季
抹茶落季 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:53

    First, throwing exceptions from toString() is a really bad idea. toString() is used in a lot of system software (e.g. debugger) to generate the representation of the object.

    The first preference would be to do something else, maybe create a different method that may throw, and in toString() call that method, catch the exception and produce replacement output such as

    super().toString() + " threw " + exception.toString();
    

    If you feel that you really must throw, you can do this:

        try
        {
            str.insert(str.length(), current.element().toString() + " ");
            current = fList.next(current);
        }
        catch(Exception e){
           throw new IllegalStateExcception(super.toString(), e);
        }
    

    This wraps a checked exception (derived from java.lang.Exception) in an unchecked exception (derived from java.lang.RuntimeException). No need to add a throws clause.

提交回复
热议问题