throwμ throwsλ μλ°μμ μμΈ μ²λ¦¬μ κ΄λ ¨λ ν€μλλ‘, μμΈλ₯Ό λ€λ£¨λ λ° μ¬μ©λ©λλ€.
μμΈ λ°μμν€κΈ° - throw
μμΈκ° λ°μν μν©μ νμ¬ μμΉμμ μ§μ μ²λ¦¬νκΈ° μ΄λ ΅κ±°λ μ²λ¦¬ν μ μλ κ²½μ°μ throw λ¬Έμ μ¬μ©νμ¬ μμΈλ₯Ό λμ§λλ€. μ΄κ²μ μμΈλ₯Ό νμ¬ μμΉμμ λ°μμν€λ κ²μ μλ―Έν©λλ€. κ·Έλ¦¬κ³ μ΄ μμΈλ νΈμΆ μ€νμ λ°λΌ μμ νΈμΆμλ‘ μ νλ©λλ€.
try {
Exception e = new Exception("κ³ μλ‘ λ°μμν΄"); // μμΈ ν΄λμ€ μμ±
throw e; // μμΈ λ°μμν€κΈ°
// throw new Exception("κ³ μλ‘ λ°μμν΄"); μμ λ μ€μ ν μ€λ‘
} catch (Exception e) {
System.out.println("μλ¬ λ©μΈμ§ : " + e.getMessage());
e.printStackTrace();
}
System.out.println("νλ‘κ·Έλ¨ μ μ μ’
λ£");
μμΈ λμ§κΈ° - throws
throwsλ μλ°μμ λ©μλ μ μΈλΆμμ μ¬μ©λλ©°, ν΄λΉ λ©μλμμ λ°μν μ μλ μμΈλ₯Ό λμ΄νλ λ° μ¬μ©λ©λλ€. μ΄ ν€μλλ λ©μλλ₯Ό νΈμΆνλ μ½λμμ ν΄λΉ μμΈλ₯Ό μ²λ¦¬νλλ‘ κ°μ νλ μν μ ν©λλ€. μ¦, throwsλ₯Ό μ¬μ©νλ©΄ λ©μλμμ μμΈλ₯Ό μ§μ μ²λ¦¬νμ§ μκ³ , νΈμΆμμκ² μμΈ μ²λ¦¬λ₯Ό μμν©λλ€.
try {
calculate();
} catch (Exception e) {
System.out.println("μμΈκ° λ°μνμ΅λλ€: " + e.getMessage());
}
}
public static void calculate() throws Exception {
try {
divideByZero();
} catch (ArithmeticException e) {
System.out.println("0μΌλ‘ λλκΈ° μμΈ λ°μ");
throw e; // μμΈλ₯Ό νΈμΆμμκ² λ€μ λμ§
}
}
public static void divideByZero() {
int dividend = 10;
int divisor = 0;
int result = dividend / divisor;
}
λ©μλκ° μ΄λ€ μμΈλ₯Ό λμ§ μ μλμ§ throwsλ₯Ό ν΅ν΄ λͺ
μνλ©΄, ν΄λΉ λ©μλλ₯Ό μ¬μ©νλ μ½λμμλ try-catch λΈλ‘μ μ¬μ©νκ±°λ, μμΈλ₯Ό λ λμ μμ€μΌλ‘ μ νν μ μμ΅λλ€.
throwsλ μμΈμ μ²λ¦¬λ₯Ό νΈμΆμμκ² μμν¨μΌλ‘μ¨ μ½λμ λͺ¨λμ±κ³Ό κ°λ μ±μ ν₯μμν¬ μ μμ΅λλ€. λν, μμΈμ μΈλΆ μ¬νμ λ©μλ μκ·Έλμ²μ λͺ μν¨μΌλ‘μ¨ ν΄λΉ λ©μλλ₯Ό μ¬μ©νλ κ°λ°μμκ² μ΄λ€ μμΈλ₯Ό μ²λ¦¬ν΄μΌ νλμ§ μλ €μ£Όλ μν μ ν©λλ€.
When you encounter an exceptional condition that you want to handle at a higher level or in a different part of the program, you can use the throw statement.
The ‘throws’ keyword used to pass an exception to another location for handling.
'Programming > Java' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
24 Enum (0) | 2024.01.21 |
---|---|
23 Annotation (1) | 2024.01.21 |
21 Exception handling (0) | 2024.01.21 |
20 Exceptions (0) | 2024.01.21 |
19 Interface (0) | 2024.01.20 |
λκΈ