Java Runtime Exceptions You Need to Avoid
Expressions
Divisor is zero
Exception:
java.lang.ArithmeticException
Error code example:
int a = 1; |
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); |
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; |
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(); |
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); |
Suggestion:
If you need update the list later, you should use new ArrayList(Arrays.asList())
instead of Arrays.asList()
.