I do not really have a problem to solve, I would just like to know if there is a common way to deal with the following:
I have a constructor that takes two arguments (both int). The constructor itself only initializes attributes of my object. However, if (arg1 > arg2)
is not fulfilled, there will be problems later on. Therefore I want to throw an Exception
here because this is the place where a potential problem originates.
Is there a common Exception
to throw in this case? Or would you rather throw a custom Exception
? If so, how would you call that?
Is there a common
Exception
to throw in this case?
According to the documentation , an IllegalArgumentException
can be thrown:
Thrown to indicate that a method has been passed an illegal or inappropriate argument .
Or would you rather throw a custom
Exception
?
It's not the case for throwing own exception unless you already have one and there are a few similar situations where you have thrown it.
Try to answer the following questions, they are gonna point you to the answer:
This is a good reason to use IllegalArgumentException
. You can use it in your class that way:
class YourClass {
int first, second;
YourClass(int first, int second) {
if(first <= second) {
throw new IllegalArgumentException("First argument has to be higher than second, arguments passed: " + first + ", " + second);
}
this.first = first;
this.second = second;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.