Skip to content

Instantly share code, notes, and snippets.

@MWhyte
Last active December 8, 2021 20:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MWhyte/8c4dd1dbcf3a556d9cd777503bf5c521 to your computer and use it in GitHub Desktop.
Save MWhyte/8c4dd1dbcf3a556d9cd777503bf5c521 to your computer and use it in GitHub Desktop.
Post: Exception Handling in Java
A Post: Exception Handling in Java
package dev.mwhyte.errors;
import java.util.ArrayList;
import java.util.List;
public class OOMExample {
private final List<Integer> scores = new ArrayList<>();
public void addScore(Integer score) {
scores.add(score);
}
public List<Integer> getScores() {
return scores;
}
}
package dev.mwhyte.errors;
import static org.junit.Assert.assertThrows;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class OOMExampleTest {
private OOMExample oomExample;
@BeforeEach
void setUp() {
oomExample = new OOMExample();
}
@Test
void addScore_smallNumbers() {
for (int i = 0; i < 100; i++) {
oomExample.addScore(i);
}
assertEquals(100, oomExample.getScores().size());
}
@Test
void addScore_largeNumbers() {
assertThrows(OutOfMemoryError.class, () -> {
for (int i = 0; i < Integer.MAX_VALUE; i++) {
oomExample.addScore(i);
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment