Hello! Pretty new to programming in general, and in working on a class assignment (data structures) I've hit a scenario where I'm not sure what is the best way to proceed.
Say we're creating an object with a String attribute. Now say, we want to make sure this String attribute is never an empty string. It looks like I can handle this two ways:
1) check the input prior to creating the object, like so:
2) Have the constructor throw an exception if the String it's passed is empty:
So I guess my question really is: Do we use exceptions to check business logic? Or is that something that should be kept outside the scope of the object itself?
Say we're creating an object with a String attribute. Now say, we want to make sure this String attribute is never an empty string. It looks like I can handle this two ways:
1) check the input prior to creating the object, like so:
Code:
public class TestIfElse {
private String name;
public TestIfElse(String name) {
this.name = name;
}
public static void main(String[] args) {
String input = "";
if ( input.isEmpty() ) {
System.out.println("The name must not be empty");
} else {
TestIfElse thing = new TestIfElse(input);
}
}
}
2) Have the constructor throw an exception if the String it's passed is empty:
Code:
public class TestException {
private String name;
public TestException (String name) {
if (name.isEmpty()) {
throw new IllegalArgumentException("name can not be empty");
}
this.name = name;
}
public static void main(String[] args) {
String input = "";
try {
TestException thing = new TestException(input);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
}
So I guess my question really is: Do we use exceptions to check business logic? Or is that something that should be kept outside the scope of the object itself?
