Как сделать так чтобы пробросилось исключение для пустого списка?

public double getBottomBorder() {
    double max = ships.get(0).y + ships.get(0).height;
        for (EnemyShip enemyShip : ships) {
            if (enemyShip.y + enemyShip.height > max)
                max = enemyShip.y + enemyShip.height;
        }
    try {
        return max;
    } catch (NoSuchElementException e){
        return 0;
    }
}

Ответы (1 шт):

Автор решения: Aziz Umarov

попробуйте так

public double getBottomBorder() {
 try {
 double max = ships.get(0).y + ships.get(0).height;
     for (EnemyShip enemyShip : ships) {
         if (enemyShip.y + enemyShip.height > max)
             max = enemyShip.y + enemyShip.height;
     }

     return max;
 } catch (NoSuchElementException e){
     return 0;
 }
 catch(NullPointerException e) {
     return 0;
 }
}    

ну или по рекомендациям

public double getBottomBorder() {
 try {
  if (ships != null && !ships.isEmpty()) {
     double max = get(0).y + ships.get(0).height;
     for (EnemyShip enemyShip : ships) {
         if (enemyShip.y + enemyShip.height > max)
             max = enemyShip.y + enemyShip.height;
     }    
     return max;
    } else {
      throw new NoSuchElementException(); 
   }  
 } catch (NoSuchElementException e){
     return 0;
 }     
}
→ Ссылка