Java-重写Object的toString()方法,但我必须抛出异常

Java-重写Object的toString()方法,但我必须抛出异常

问题描述:

我遇到了一个问题,我必须重写Object的toString()方法,但是原始方法不会引发任何异常.但是,我正在使用一些需要引发异常的通用代码.

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 that requires exceptions to be thrown.

public String toString() throws EmptyListException, InvalidPositionException
{
    Position<Entry<E>> current = fList.first();
    StringBuilder str = new StringBuilder();
    for(int i = 0; i < size(); i++)
    {
        try
        {
            str.insert(str.length(), current.element().toString() + " ");
            current = fList.next(current);
        }
        catch(Exception e){}
    }
    return str.toString();
}

这是FavoriteList.java的一部分.这些异常必须抛出.如果有某种方法可以抑制这些异常或将它们捕获到方法中,那将很有帮助.

This is part of FavoriteList.java. These exceptions HAVE to be thrown. If there is any way to somehow suppress these exceptions or catch them inside the method, that would be helpful.

最后,我的方法标题必须如下所示:

In the end, my method header has to look like this:

public String toString()
{ content }

我不在乎方法的结尾内容.只要编译就可以了.我只需要修复标题,但是找不到解决方法.提前非常感谢您.

I don't care about the ending content of the method. As long as it compiles I am fine. I just need to fix the header, but I can't find a way to fix it. Thank you very much in advance.

首先,从 toString()抛出异常是一个非常糟糕的主意. toString()在许多系统软件(例如调试器)中用于生成对象的表示形式.

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.

第一个优先选择是做其他事情,也许创建一个可能抛出的不同方法,然后在 toString()中调用该方法,捕获异常并产生替换输出,例如

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);
    }

这将检查的异常(从java.lang.Exception派生)包装在未检查的异常(从java.lang.RuntimeException派生)中.无需添加 throws 子句.

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.