How do I throw multiple exceptions in one constructor? [duplicate] - java

This question already has answers here:
Comparing objects never returns true
(4 answers)
Closed 5 years ago.
I was wondering how can I execute both of these exceptions in the same constructor. My program compiles fine, but it won't throw the exception for the second if statement.
public Segment(Point firstPoint, Point secondPoint) {
if(firstPoint == null || secondPoint == null)
throw new IllegalArgumentException("Cannot pass a null value");
if(firstPoint == secondPoint)
throw new IllegalArgumentException("Segment cannot be 0");
this.endPoint1 = new Point(firstPoint);
this.endPoint2 = new Point(secondPoint);
}

What do you mean by throwing two exceptions? If you make throw, than method stops. If you need to combine messages, so you can do something like this:
//Parameterized constructor
public Segment(Point firstPoint, Point secondPoint)
{
String error = "";
if(firstPoint == null || secondPoint == null) {
error = "Cannot pass a null value";
}
if(firstPoint == secondPoint) {
error = error.equals("") ?
"Segment cannot be 0" :
error + ". Segment cannot be 0"
}
if (!error.equals("")){
throw new IllegalArgumentException("Segment cannot be 0");
}
this.endPoint1 = new Point(firstPoint);
this.endPoint2 = new Point(secondPoint);
}

Related

Not able to remove null from a list in Java [duplicate]

This question already has answers here:
Why do I get a NullPointerException when comparing a String with null?
(4 answers)
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 days ago.
I have a list of a bean class newSRMAPIResponseBeanList wherein I am always getting a null object at last which I am trying to remove but it is resulting in null pointer exception if I handle the exception, it is not removing that null value. Below is my code.
for (int i = 0; i < newSRMAPIResponseBeanList.size(); i++) {
try {
if (newSRMAPIResponseBeanList.get(i).getCompanyId().equals(null)) {
newSRMAPIResponseBeanList.remove(i);
}
}catch(Exception e) {
e.printStackTrace();
}
}
In the if condition itself it is failing. I want to remove the null value of company ID. Actually newSRMAPIResponseBeanList is a list of List<NewSRMAPIResponseBean> newSRMAPIResponseBeanList = new ArrayList<>(); and the bean class is as follows.
public class NewSRMAPIResponseBean {
private String companyId;
private String investmentId;
private String performanceId;
private List<String> values;
}
Is there any way I can remove that null value? I also tried using Java streams as follows.
List<NewSRMAPIResponseBean> finalList=newSRMAPIResponseBeanList.parallelStream()
.filter(Objects::nonNull)
.collect(Collectors.toList());
This too did not work.
I want to remove the null value of company ID.
I presume you mean remove the list element if the Id is null. So It's not the bean that is null, it is the companyId. Assuming you have getters, try it like this. If the Id is not null, let it pass thru.
List<NewSRMAPIResponseBean> finalList=newSRMAPIResponseBeanList.parallelStream()
.filter(bean->bean.getCompanyId() != null)
.collect(Collectors.toList());
You can also do it in a simple loop.
To avoid a ConurrentModificationException, use an iterator.
Iterator<NewSRMAPIResponseBean> iter = newSRMAPIResponseBeanList.iterator();
while (iter.hasNext()) {
if (iter.next().getCompanyId() == null) {
iter.remove();
}
}

Although my code is returning String the function still expects to return string [duplicate]

This question already has answers here:
Java: missing return statement after try-catch [duplicate]
(4 answers)
Closed 4 years ago.
// Even after returning the success message i am still getting String return expected...
// Any help will be appreciated
public String addStudent(Student student) throws Exception
{
try
{
Validator validate = new Validator();
validate.validate(student);
if((student.getMark1()<50 && student.getMark2()<50 && student.getMark3()<50) && student.getResult()=='P')
throw new Exception("Service.INVALID_RESULT_PASS");
if((student.getMark1()>=50 || student.getMark2()>=50 || student.getMark3()>=50) && student.getResult()=='F')
throw new Exception("Service.INVALID_RESULT_FAIL");
return "Success";
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
If you mean that your IDE is saying that it still wants a return, its because the code is not guarrenteed to return something. It doesn't return something if an exception is thrown, so try returning something at the end of the code, like:
catch(Exception e)
{
System.out.println(e.getMessage());
}
return "";
}
(I haven't typed all the code, but you get the point)
The issue is that you aren't telling Java what to return if an Exception is caught. You will need to add a return statement to your catch block or outside the try/catch block.
That being said, you are throwing a new Exception from within your try/catch block, which is odd.
If you want to throw those Exceptions yourself, then the try/catch is not needed here.

NullPointerException when validtion object [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I get NullPointerException when validating object. I send to controller dto, and when validating it. I cant understan where is the problem because product that goes into validate method is not null, Validator code :
#Override
public void validate(Object o, Errors errors) {
Product product = (Product) o;
if (product.getTitle().isEmpty() || product.getTitle() == null) {
errors.rejectValue("title", "product.title", "Product title cant be empty");
}
if (product.getDescription().isEmpty() || product.getDescription() == null) {
errors.rejectValue("description", "product.description", "Product description cant be empty");
}
if (product.getPrice().isNaN() || product.getPrice()<=0 || product.getPrice() == null) {
errors.rejectValue("price", "product.price", "Product price is not valid");
}
if (product.getCategory()==null) {
errors.rejectValue("category", "product.category", "Product category is not valid");
}
}
and i get this
java.lang.NullPointerException
com.shop.validator.ProductValidator.validate(ProductValidator.java:27)
com.shop.controller.ProductController.createProduct(ProductController.java:82)
com.shop.controller.ProductController$$FastClassBySpringCGLIB$$c0d382c4.invoke()
org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
|| evaluates from left to right. So if you say
x == null || x.somethingSomething()
and if x is null, the first condition will catch the case, and it will prevent the method call on a null reference from happening. But if you say
x.somethingSomething() || x == null
and if x is null, it tries to evaluate the method call first, and throws an exception before it gets to the null check. Java (or any other computer language I'm aware of) isn't smart enough to "figure out" to do the null check first. It trusts the order you give it.
Similarly with &&:
if (x != null && x.something())
will do the null check at the right time, but
if (x.something() && x != null)
won't.

Check if Object has data or not?

I am calling method to get data as per passed text that will ping into database.
So I want to check if there is data arrived in object or not.
Code :
Method m = service.getMethodDataByFilter(text);
I have tried :
if(m == null){
System.out.println("In NULL");
}
but it does not entering inside it.
I have also tried :
if(m.getName().isEmpty()){
System.out.println("In NULL");
}
then it throws NPE in condition because no data received.
So how to check if there is data inside object or not ?
Method Class :
public class Method {
private Integer id;
private String name;
// getter-setter
}
UPDATE
Have just try Ruchira
if(m== null){
System.out.println("m is null");
}else if(m.getName()==null){
System.out.println("m.getName() is null");
}else if(m.getName().isEmpty()){
System.out.println("m.getName() is empty");
}
Still throws same NPE.
FULL Method Code :
public MethodDTO getMethod(String text){
Method m = service.getMethod(text);
if(m == null){
System.out.println("m is null");
}else if(m.getName()==null){
System.out.println("m.getName() is null");
}else if(m.getName().isEmpty()){
System.out.println("m.getName() is empty");
}
ModelMapper mapper = ModelMap.methodMapper();
return mapper.map(m, MethodDTO.class);
}
Try this if ( m == null || m.getName()== null). Note that apart from m its name may also be null.
You need to change your code to :
if(myObject==null){ // check if object is null
System.out.println("myObject is NULL");
}
else{ // myObject should not be null here
if(myObject.getField1()==null) // check for fields within the object
{
System.out.println("field1 is NULL");
}
if(myObject.getField2()==null)
{
System.out.println("field2 is NULL");
}
...
}
Note if the object is null, then trying to access any non-static field / method on it will result in NPE.
Explanation.
if(m == null){
System.out.println("In NULL");
}
Since inside if not enter since m is not null. But
if(m.getName().isEmpty()){
System.out.println("In NULL");
}
Here you get NullPointerException since m.getName() is null.
So you can try as follows
if(m == null){
System.out.println("m is null");
}else if(m.getName()==null){
System.out.println("m.getName() is null");
}else if(m.getName().isEmpty()){
System.out.println("m.getName() is empty");
}
m == null
will return false when object m is not null but it does not check all its attributes recursively inside object.
m.getName()
seems to be returning null but even this statement will not throw NPE. But yes if you call m.getName().isEmpty() will throw NPE. You should better check like this:
if (m.getName() == null) //assuming you have already checked for m being null
Check the object is null or not like this:
if(m != null && m.getName != null) {
// Object m is not null and m.getName is also not null
} else {
// Either Object m is null or m.getName is null or both are null
}

Error Checking a project in Java

My goal in the below code is to check for input that is longer than two places after the decimal point, then throw an exception. I cant seem to get it correct though. I am trying to use indexOf to get to the decimal point and then I want to check the length of the portion after it. If it is greater than 2 I want it to throw the exception. Anybody have some tips for this situation?
public ChangeJar(final String amount) {
int i = amount.indexOf('.');
String temp = amount.substring(i + 2);
if(temp.length() > 2 ){
throw new IllegalArgumentException("Too many decimal places!");
}
if (amount == null || Double.parseDouble(amount) < 0) {
throw new IllegalArgumentException("amount cannot be null!");
}
double amt;
try {
amt = Double.parseDouble(amount);
} catch (NumberFormatException ex) {
throw new IllegalArgumentException("Invalid entry. Format is 0.00.");
}
amountHelper(amt);
}
I also wanted to know how I could add error checking to this constructor as I dont want null inputs. I get an error when trying to add error checking that says the constructor call must be the first statement in the method.My code for the constructor is:
public ChangeJar(final ChangeJar other){
if(other == null){
throw new IllegalArgumentException("Values cannot be null!");
}
this(other.quarters, other.dimes, other.nickels, other.pennies);
}
All suggestions are appreciated!
As Java does not allow to put any statements before the super or constructor calls in a constructor. Hence you cant do this:
public ChangeJar(final ChangeJar other){
if(other == null){
throw new IllegalArgumentException("Values cannot be null!");
}
this(other.quarters, other.dimes, other.nickels, other.pennies);
}
You may add the check in the constructor that you are calling.

Categories

Resources