Back to questions
JuniorTheoryCommon
What does the program print?
import java.util.HashSet;
public class Main {
static HashSet<String> out = new HashSet<>();
static void borrow(String t) throws LoanException { if (!out.add(t)) throw new LoanException(t); }
public static void main(String[] args) {
try {
borrow("Dune");
borrow("Dune");
} catch (LoanException e) { System.out.println(e.getMessage()); }
}
}
class LoanException extends Exception { LoanException(String t) { super(t + " is out"); } }Dune is out
- Expecting
Dune:getMessage()returns what the constructor passed tosuper, and this constructor adds" is out"to the title. - Expecting nothing to be printed:
addreturnsfalsefor an element the set already holds, so the secondborrowthrows andcatchprints the message.
- What does the program print if the second call is
borrow("Emma")? - Why must
maincatchLoanException, and what changes if the class extendsRuntimeException?