Context: I am writing a semaphore class for school, and one of the requirements is that it may not be initialized with a negative value.
Right now my constructor throws an exception:
/**
* Constructor
*/
public Semaphore(int value) throws Exception
{
if (value < 0)
throw new Exception("Negative value provided for initial constructor.");
this.value = value;
}
Handling an exception in order to instantiate a semaphore seems overly heavy to me, so I am considering quietly setting any negative values to zero, ie:
/**
* Constructor
*/
public Semaphore(int value)
{
if (value < 0)
this.value = 0;
else
this.value = value;
}
You should use the IllegalArgumentException instead. It requires no explicit exception handling and it behaves exactly like you want, that is to signal an illegal argument.
If you say: Hey, the values are directly from the user. Correct them with a message.
If you say: Hey, the values are generated and a bug produced a negative value.
throw new IllegalArgumentException("Negative Value",
new IndexOutOfBoundsException(value+""));
If you say: Hey, i like to let the VM decide to throw or correct. Use assert value > 0;.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With