nus-cs2113-AY2021S2 / forum

5 stars 0 forks source link

How to condense all my exceptions into a small exception "Duke Exception"? #36

Closed Leeyp closed 3 years ago

Leeyp commented 3 years ago

try { Parser.executeCommand(Parser.input, command); } catch (InvalidCommandException e) { Ui.showInvalidCommandError(); } catch (EmptyInputException e) { Ui.showEmptyInputError(); } catch (StringIndexOutOfBoundsException e) { Ui.showNoTimeAddedError(); } catch (InvalidEventTimeException e) { Ui.showInvalidEventTimeError(); } catch (InvalidDeadlineTimeException e) { Ui.showInvalidDeadlineTimeError(); } catch (NumberFormatException e) { Ui.showInvalidIntegerTaskIndexError(); } catch (IndexOutOfBoundsException e) { Ui.showTaskIndexNotExistsError(); }

The above is my code. As you can see, there are many exceptions I tried to catch. But, I didn't know you can shrink them all down to this:

public void run() { ui.showWelcome(); boolean isExit = false; while (!isExit) { try { String fullCommand = ui.readCommand(); ui.showLine(); // show the divider line ("___") Command c = Parser.parse(fullCommand); c.execute(tasks, ui, storage); isExit = c.isExit(); } catch (DukeException e) { ui.showError(e.getMessage()); } finally { ui.showLine(); } } } image Source: Week 7, A-MoreOOP. How to do that?

okkhoy commented 3 years ago

I don't see a problem in the way you are doing (catching many different exceptions). In fact, that seems the right way, where you are handling individual exceptions separately, differently. When you make all under DukeException it becomes a broad-based catching.

Even if you make all the custom exceptions sub-classes of DukeException, it is best to catch them individually (child-first, parent-next).

Leeyp commented 3 years ago

Great, thank you prof. I will leave it like this then. I was just concerned if it was too long or ugly.