rspec/rules/S3472/java/rule.adoc

64 lines
1.1 KiB
Plaintext
Raw Permalink Normal View History

== Why is this an issue?
2021-04-28 16:49:39 +02:00
Returning ``++null++`` when something goes wrong instead of throwing an exception leaves callers with no understanding of what went wrong. Instead, an exception should be thrown.
=== Noncompliant code example
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
public MyClass readFile(String fileName) {
MyClass mc;
try {
// read object from file
} catch (IOException e) {
// do cleanup
return null; // Noncompliant; why did this fail?
}
return mc;
}
----
=== Compliant solution
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
public MyClass readFile(String fileName) throws IOException{
MyClass mc;
try {
// read object from file
} catch (IOException e) {
// do cleanup
throw e;
}
return mc;
}
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Throw an exception instead of returning null
=== Highlighting
primary: return statement
'''
== Comments And Links
(visible only on this page)
=== on 14 Dec 2015, 09:39:28 Nicolas Peru wrote:
LGTM but I lack a reference or source for this rule.
endif::env-github,rspecator-view[]