Java Runtime Exceptions You Need to Avoid

Expressions

Divisor is zero

Exception:

java.lang.ArithmeticException

Error code example:

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:

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:

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:

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:

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().