If your class has a no-argument constructor and setters, you need to check it for validity. You could introduce a method
boolean valid()
that returns true
if the instance has all tha it needs.
문제
Customer Class:
public class Customer {
String name;
String password;
String Address;
int age;
//and getter setter of the above fields
}
In Main method:
Customer customer = new Customer();
customer.setName(null);
customer.setAge(25);
customer.setAddress("Address");
In the main method name field sets with null, and password is NOT even set a value. In this case, if no values set needs to throw user defined Exception.
UPDATE #1: if suppose out of 100 fields in a Customer class, any one of the field has null or empty then need to throw InadequateResourceException. How can I proceed with?
Thanks in advance!
해결책
If your class has a no-argument constructor and setters, you need to check it for validity. You could introduce a method
boolean valid()
that returns true
if the instance has all tha it needs.
다른 팁
Define your own custom exception and throw that.
How to implement custom exception? you can try something similar to following.
public class MyException extends Exception{
public MyException() {
super();
}
public MyException(Exception e) {
super(e);
}
public MyException(String message, Exception e) {
super(message, e);
}
public MyException(String message) {
super(message);
}
}
To guarantee all Customers have their necessary values assigned, define a single Constructor that clearly states the obligatory fields:
public Customer(String name, String password)
{
this.name = name;
this.password = password;
}
You can also test the parameters for nullness, emptiness, etc. and throw a IllegalArgumentException if needed.