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

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

    If you really need to throw an exception without surrounding your code with a try and catch

    @override
    public String toString(){
         if(...)throw new IllegalStateException("list is empty");
         else if(...)throw new IllegalStateException("position is invalid"); 
         return ...;
    }
    

提交回复
热议问题