Contents
  1. 1. Expressions
    1. 1.1. Divisor is zero
  2. 2. Statements
    1. 2.1. Update a collection in for loop (Fail fast)
  3. 3. Objects and Classes
    1. 3.1. Call a null object methods
  4. 4. Collections
    1. 4.1. Add elements to Collections.emptyList()
    2. 4.2. Add elements to List built by Arrays.asList()

Expressions

Divisor is zero

Exception:

java.lang.ArithmeticException

Error code example:

1
2
3
int a = 1;
int b = 0;
int result = a / b;

Suggestion:

You need to check if the divisor is zero.

Statements

Update a collection in for loop (Fail fast)

Exception:

java.lang.UnsupportedOperationException

Error code example:

1
2
3
4
5
6
7
8
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6);
for (int i = 0; i < list.size(); i++) {
Integer value = list.get(i);
System.out.println(value);
if (value == 1) {
list.add(100); // or list.remove(0);
}
}

Suggestion:

Do not insert, update, and delete elements of a collection while looping through the collection.

Objects and Classes

Call a null object methods

Exception:

java.lang.NullPointerException

Error code example:

1
2
User user = null;
String name = user.getName();

Suggestion:

You need to check if the object is null when calling its methods.

Collections

Add elements to Collections.emptyList()

Exception:

java.lang.UnsupportedOperationException

Error code example:

1
2
List<Integer> list = Collections.emptyList();
list.add(1);

Suggestion:

Don’t return Collections.emptyList() in intermediate methods.

Add elements to List built by Arrays.asList()

Exception:

java.lang.UnsupportedOperationException

Error code example:

1
2
List<Integer> list = Arrays.asList(1, 2, 3);
list.add(4);

Suggestion:

If you need update the list later, you should use new ArrayList(Arrays.asList()) instead of Arrays.asList().

Contents
  1. 1. Expressions
    1. 1.1. Divisor is zero
  2. 2. Statements
    1. 2.1. Update a collection in for loop (Fail fast)
  3. 3. Objects and Classes
    1. 3.1. Call a null object methods
  4. 4. Collections
    1. 4.1. Add elements to Collections.emptyList()
    2. 4.2. Add elements to List built by Arrays.asList()