-1

I'm adding multiple players to a team and each individual player needs a try catch, but the catch is always the same

try{
    team.addPlayer( new Player( 1, "PLYR1" ) );
} catch ( Exception e ){
     System.out.println( e.toString() );
}

try {
     team.addPlayer( new Player( 2, "PLYR2" ) );
} catch ( Exception e ){
     System.out.println( e.toString() );
}

Is there any way to simplify this?

Maroun
  • 94,125
  • 30
  • 188
  • 241
CrazineX
  • 3
  • 1
  • 3
    You can add the players in the same `try` clause, and have only one `catch`. – Maroun Mar 08 '19 at 11:08
  • 3
    The answer is yes, but the exact way you would do it depends on what behaviour you want. For example, if adding player 1 fails do you want to try adding player 2 or do you want to stop? – Steve Bosman Mar 08 '19 at 11:12
  • Possible duplicate of [Multiple or Single Try Catch](https://stackoverflow.com/questions/4555322/multiple-or-single-try-catch) – Googlian Mar 08 '19 at 11:14

3 Answers3

1

as saying at your comments you can use this

try{
    team.addPlayer( new Player( 1, "PLYR1" ) );
    team.addPlayer( new Player( 2, "PLYR2" ) );
} catch ( Exception e ){
     System.out.println( e.toString() );
}

of if you care about if the first player is added, use this:

try{
    team.addPlayer( new Player( 1, "PLYR1" ) );
    try {
         team.addPlayer( new Player( 2, "PLYR2" ) );
    } catch ( Exception e ){
         System.out.println( e.toString() );
    }
} catch ( Exception e ){
     System.out.println( e.toString() );
}
1

you can try this code instead of using two try blocks.

try{
    team.addPlayer( new Player( 1, "PLYR1" ) );
     team.addPlayer( new Player( 2, "PLYR2" ) );
} 
catch ( Exception e ){
     System.out.println( e.toString() );
}
Pallu
  • 11
  • 2
0

If you want to iterate through all possible players using catch and throw the same error to stdout if an exception occurs you should use a basic for loop.

Player class is assumed to be defined and team object created:

String[] players = {"PLYR1", "PLYR2", "PLYR3"}

for (String player: players) {
  try{
      team.addPlayer( new Player( 1, player ) );
  } catch ( Exception e ){
       System.out.println( e.toString() );
  }
}
Szymon Maszke
  • 22,747
  • 4
  • 43
  • 83