How to check emptiness and null for all fields in a Class and implement user-defined exception? [closed]

StackOverflow https://stackoverflow.com/questions/21671796

  •  09-10-2022
  •  | 
  •  

문제

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top