Avoid the use of in-band error indicators. These They are much less common in Java than in some other programming languages, but they are used in the read(byte[] b, int off, int len)
and read(char[] cbuf, int off, int len)
family of methods in java.io
.
In Java, the best way to indicate an exceptional situation is by throwing an exception , rather than by returning an error code. Exceptions cannot be ignored in the same way that error codes can, and exceptions are propagated across scopes. When using exceptions, the error-detection and error-handling code is kept separate from the main flow of control. Also, exceptions can be used in situations where error codes cannot be returned (in constructors, for example).
...
This noncompliant code example attempts to read into an array of characters and the add an extra character into the buffer immediately after the characters read.
...
However, if the input buffer is initially at end-of-file, then the read
method will return -?1 and the attempt to place the termintor terminator character will throw an ArrayIndexOutOfBoundsException
.
...
This guideline appears in the C Secure Coding Standard as ERR02-C. Avoid in-band error indicators and in the C++ Secure Coding Standard as ERR07-CPP. Use exception handling rather than error codes.
...
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="43ff559f5e25168e-3abe2740-44a44432-8ebbbfc8-362d3716bf767e51afb94767"><ac:plain-text-body><![CDATA[ | [[API 2006 | AA. References#API 06]] | [Class Reader | http://download.oracle.com/javase/6/docs/api/java/io/Reader.html] | ]]></ac:plain-text-body></ac:structured-macro> |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="fba14b9c3960250b-3e06bbcf-46e54823-8a68a8f2-db4cacec8e01916f4dadfd4d"><ac:plain-text-body><![CDATA[ | [[JLS 2011 | AA. References#JLS 11]] | Chapter 11. , Exceptions | ]]></ac:plain-text-body></ac:structured-macro> |