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
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.