73 lines
1.9 KiB
Plaintext
73 lines
1.9 KiB
Plaintext
This issue indicates that an exception will be thrown because a method is used incorrectly.
|
|
To fix it, check the requirements of the method and fulfill them.
|
|
|
|
== Why is this an issue?
|
|
|
|
It is common for methods to check the value of their parameters or the state of
|
|
their associated object and throw an exception when one of them does not match a
|
|
given condition.
|
|
Those conditions are usually mentioned in the javadoc of the method.
|
|
|
|
This rule raises an issue when it detects that a method call will trigger one of
|
|
the following exceptions:
|
|
|
|
* `java.lang.IllegalArgumentException`
|
|
* `java.lang.IllegalStateException`
|
|
|
|
=== What is the potential impact?
|
|
|
|
include::../../../shared_content/layc/exception-impact.adoc[]
|
|
|
|
== How to fix it
|
|
|
|
=== Code examples
|
|
|
|
==== Noncompliant code example
|
|
|
|
[source,java,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
/**
|
|
* Set the oven temperature
|
|
* @param temp the temperature in Celsius, between 0 and 250 (inclusive)
|
|
* @throws IllegalArgumentException if the temperature is outside of the supported range
|
|
*/
|
|
void setOvenTemperature(int temp) {
|
|
if (temp < 0 || temp > 250) {
|
|
throw new IllegalArgumentException();
|
|
}
|
|
// ...
|
|
}
|
|
|
|
void caller() {
|
|
setOvenTemperature(-3);
|
|
}
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source,java,diff-id=1,diff-type=compliant]
|
|
----
|
|
/**
|
|
* Set the oven temperature
|
|
* @param temp the temperature in Celsius, between 0 and 250 (inclusive)
|
|
* @throws IllegalArgumentException if the temperature is outside of the supported range
|
|
*/
|
|
void setOvenTemperature(int temp) {
|
|
if (temp < 0 || temp > 250) {
|
|
throw new IllegalArgumentException();
|
|
}
|
|
// ...
|
|
}
|
|
|
|
void caller() {
|
|
setOvenTemperature(180);
|
|
}
|
|
----
|
|
|
|
== Resources
|
|
|
|
=== Documentation
|
|
|
|
* https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/IllegalArgumentException.html[IllegalArgumentException]
|
|
* https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/IllegalStateException.html[IllegalStateException]
|