Saibo-creator
Saibo-creator

Reputation: 2201

Exception handling in Java: catch and throw again

I'm following a Java programming course and we just learned Exception Handling in Java. I saw this code in the last homework correction:

public int getWinner() throws IllegalArgumentException {
  int winner;

  try {
    winner = GameRules.getWinner(firstPlayer, secondPlayer);
  } catch (IllegalArgumentException e) {
    throw e;
  }

  return winner;
}

My question would be: Why do we first catch the Exception e and throw it again? I think if you do so, then the program will still be stoped so it's like not handling the exception. Maybe I am wrong, please point it out, thanks!

Upvotes: 0

Views: 488

Answers (1)

Rob Evans
Rob Evans

Reputation: 2874

Sometimes you catch an exception as you want to perform some logging/record some metrics as part of the process. Re-throwing the exception means you can then pass the exception higher up the call-stack so it can be dealt with by a (centralised) error handler.

Not all exceptions are unrecoverable just because they occur, so throwing an exception doesn't necessarily cause the application to stop unless its allowed to bubble all the way up the call stack.

Catching the exception simply gives you the opportunity to decide what to do next when the exception occurs. Catching an exception and then ignoring it is typically bad practice.

Upvotes: 2

Related Questions