-1

My application is required to display all the empty input errors. I can do it using if-else to store all errors but according to this post, I should using try-catch block to check the required input. How can I practice using try-catch and what is the best practice? Thanks.

A example for creating user. If using if-else, the checking code should be like that

if(isEmpty(inputUserName)){
  errorList.add("User name is required");
}
if(isEmpty(inputPassword)){
  errorList.add("Password is required");
}
if(isEmpty(inputAnotherRequiredFields)){
  errorList.add("Fields is required");
}
....
Fanta
  • 1
  • 2
    It would make most sense IMO to throw an exception when you try to use the variable rather than with the code you have posted here. This could be a method that takes username and password as parameters for instance that could throw an exception if either is empty – Joakim Danielson May 07 '20 at 10:31
  • The question you linked isn't about this topic. and not one of the five answers to it says what you claim. If you use an exception for this you can only detect one error at a time. – user207421 May 07 '20 at 10:43

1 Answers1

1

Exceptions are meant for a very specific type of situation.

  • If a method is called and cannot fulfill its contract for some reason, it does not return normally, but instead throws an exception.
  • If it can fulfill its job (or its job is to find some special situations like missing values), it should return normally and present its results as return value.

So, I'd only see a reason for your code snippet to throw exceptions if it were inside some method doing business logic (e.g. bankAccountDetails(...)). This method cannot do its job if e.g. no bank account number is given, thus matching the "cannot fulfill my contract" criterion.

But I'd return an error list if you were coding something like getParameterErrors(...), because clearly it's part of this method's job to deal with missing parameters.

So, it all depends on the contract of the method you are coding.

Ralf Kleberhoff
  • 6,990
  • 1
  • 13
  • 7