item 75 jihoon - JAVA-JIKIMI/EFFECTIVE-JAVA3 GitHub Wiki
[item75] μμΈμ μμΈ λ©μμ§μ μ€ν¨ κ΄λ ¨ μ 보λ₯Ό λ΄μΌλΌ
μ€ν μΆμ (stack strace)
- μμΈλ₯Ό μ‘μ§ λͺ»ν΄ νλ‘κ·Έλ¨μ΄ μ€ν¨νλ©΄ μλ° μμ€ν μ κ·Έ μμΈμ μ€ν μΆμ (stack trace) μ 보λ₯Ό μλμΌλ‘ μΆλ ₯
- μ€ν μΆμ μ μμΈ κ°μ²΄μ toString λ©μλλ₯Ό νΈμΆν΄ μ»λ λ¬Έμμ΄λ‘, μμΈμ ν΄λμ€ μ΄λ¦ λ€μ μμΈ λ©μμ§κ° λΆλ νν
- toString λ©μλμ μ€ν¨ μμΈμ λν μ 보λ₯Ό μ΅λν λ΄λ κ²μ΄ μ€μ(μ€ν¨ μκ°μ μν©μ μ νν ν¬μ°©)
μ€ν¨ λ©μμ§ μμ± λ°©λ² λ° μ£Όμ μ¬ν
- λ°μν μμΈμ κ΄μ¬λ λͺ¨λ λ§€κ°λ³μμ νλμ κ°μ μ€ν¨ λ©μμ§μ λ΄μμΌ νλ€. μ΄λ€ λΆλΆμμ λ¬Έμ κ° λ°μνλμ§λ₯Ό μ μ μλ€.
- IndexOutOfBoundsExceptionμ μμΈ λ©μμ§λ λ²μμ μ΅μκ°κ³Ό μ΅λκ°, κ·Έλ¦¬κ³ λ²μλ₯Ό λ²μ΄λ¬λ€λ μΈλ±μ€ κ°μ λ΄μμΌ νλ€.
- μ€ν μΆμ μ 보λ λ§μ μ¬λμ΄ λ³Ό μ μμ΄, μμΈ λ©μμ§μ 보μ κ΄λ ¨ μ 보(E.g λΉλ°λ²νΈ, μνΈ ν€)λ₯Ό λ΄μμλ μ λλ€.
- λ¬Έμμ μμ€μ½λμ λν μ 보λ λ£μ§ μλ κ² μ’λ€.
- μ€ν μΆμ μλ μμΈ λ°μν νμΌ μ΄λ¦κ³Ό μ€λ²νΈ, μ€νμμ νΈμΆν λ€λ₯Έ λ©μλλ€μ νμΌ μ΄λ¦κ³Ό μ€λ²νΈκΉμ§ μ νν κΈ°λ‘λμ΄ μλ€.
- μ΅μ’ μ¬μ©μμκ²λ μΉμ ν μλ΄ λ©μμ§λ₯Ό 보μ¬μ£Όλ λ°λ©΄, μμΈ λ©μμ§λ κ°λ μ±λ³΄λ¨ λ΄κΈ΄ λ΄μ©μ΄ ν¨μ¬ μ€μνλ€.
- νμν μ 보λ₯Ό μμΈ μμ±μμμ λͺ¨λ λ°μ μμΈ λ©μμ§κΉμ§ 미리 μμ±ν΄λλ λ°©λ²λ μ’λ€.
// κΈ°μ‘΄ μ½λ public class IndexOutOfBoundsException extends RuntimeException { private static final long serialVersionUID = 234122996006267687L; public IndexOutOfBoundsException() { } public IndexOutOfBoundsException(String s) { super(s); } // Since Java9 public IndexOutOfBoundsException(int index) { super("Index out of range: " + index); } } // μκ°μ μν΄ μμ λ μ½λ public class IndexOutOfBoundsException extends RuntimeException { private final int lowerBound; private final int upperBound; private final int index; /** * IndexOutOfBoundsExceptionμ μμ±νλ€. * * @param lowerBound μΈλ±μ€μ μ΅μκ° * @param upperBound μΈλ±μ€μ μ΅λκ° + 1 * @param index μΈλ±μ€μ μ€μ ―κ° */ public IndexOutOfBoundsException(int lowerBound, int upperBound, int index) { // μ€ν¨λ₯Ό ν¬μ°©νλ μμΈ λ©μμ§λ₯Ό μμ±νλ€. // κ³ νμ§ μμΈ λ©μμ§ μμ± μ½λλ₯Ό μμΈ ν΄λμ€ μμΌλ‘ λͺ¨μμ£Όμ΄, λ©μμ§ μμ± μμ μ μ€λ³΅νμ§ μμλ λλ€. super(String.format("μ΅μκ°: %d, μ΅λκ°: %d, μΈλ±μ€: %d", lowerBound, upperBound, index)); // νλ‘κ·Έλ¨μμ μ΄μ©ν μ μλλ‘ μ€ν¨ μ 보λ₯Ό μ μ₯ν΄λλ€. this.lowerBound = lowerBound; this.upperBound = upperBound; this.index = index; } }
- μμΈλ μ€ν¨μ κ΄λ ¨λ μ 보λ₯Ό μ»μ μ μλ μ κ·Όμ λ©μλλ₯Ό μ 곡νλ κ²μ΄ μ’λ€(E.g. lowerBound, upperBound, index).
- ν¬μ°©ν μ€ν¨ μ 보λ μμΈ μν© λ³΅κ΅¬μ μ μ©νμ¬ νΉν κ²μ¬ μμΈμμ λΉμ λ°νλ€.