μμΈ μ²λ¦¬(Exception Handling)λ νλ‘κ·Έλ¨ μ€ν μ€μ λ°μνλ μμΈλ₯Ό μ μ νκ² μ²λ¦¬νλ νλ‘κ·Έλλ° κΈ°μ μ λλ€.
μμΈ μ²λ¦¬λ₯Ό ν΅ν΄ μ€νμ€μΈ νλ‘κ·Έλ¨μ μμΈ μν©μ λν λμ² λ°©λ²μ μ μνκ³ , μ μμ μΈ νλ¦μ μ μ§ν μ μμ΅λλ€. μ¦, νλ‘κ·Έλ¨μ λΉμ μμ μΈ μ’ λ£λ₯Ό λ§λ κ²μ μμΈ μ²λ¦¬μ λͺ©μ μ΄ μμ΅λλ€. μλ°μμλ try, catch, finally λΈλ‘μ μ¬μ©νμ¬ μμΈ μ²λ¦¬λ₯Ό ꡬνν©λλ€.
1) try block
→ try λΈλ‘μ μμΈκ° λ°μν μ μλ μ½λλ₯Ό ν¬ν¨νλ λΈλ‘μ λλ€. try λΈλ‘ μμμ μμΈκ° λ°μνλ©΄ ν΄λΉ μμΈλ₯Ό μ²λ¦¬νλ catch λΈλ‘μΌλ‘ μ μ΄κ° μ΄λν©λλ€.
2) catch block
→ catch λΈλ‘μ νΉμ μμΈ νμ μ λν μ²λ¦¬ μ½λλ₯Ό ν¬ν¨ν©λλ€. μ¬λ¬ κ°μ catch λΈλ‘μ μ¬μ©νμ¬ λ€μν μμΈ νμ μ λν μ²λ¦¬λ₯Ό ꡬνν μ μμ΅λλ€. μμΈκ° λ°μνλ©΄ μ μ ν catch λΈλ‘μ΄ μ νλμ΄ μ€νλ©λλ€.
3) finally λΈλ‘
→ finally λΈλ‘μ μμΈ λ°μ μ¬λΆμ κ΄κ³μμ΄ νμ μ€νλμ΄μΌ νλ μ½λλ₯Ό ν¬ν¨ν©λλ€. finally λΈλ‘μ μ νμ¬νμ΄λ©°, μλ΅ν μ μμ΅λλ€.
Try-catch μ½λ μμ
// Example 1
System.out.println(1);
try { // λκ΄νΈ νμ
System.out.println(2);
} catch (Exception e) { // μμΈ μ²λ¦¬ λΆλΆμ μ΅κ³ μ‘°μμ΄λΌ λͺ¨λ μμΈ μ²λ¦¬κ°λ₯
System.out.println(3);
}
System.out.println(4);
// κ²°κ³Ό : 1, 2, 4
// Example 2
System.out.println(5);
try {
System.out.println(0/0); // μμΈ λ°μ
System.out.println(6); // 무μ
} catch (ArithmeticException ae) { // μμΈ μ²λ¦¬ -> λ§μ½ μ²λ¦¬x? νλ‘κ·Έλ¨ λΉμ μ μ’
λ£
System.out.println(7);
}
System.out.println(8);
// κ²°κ³Ό : 5, 7, 8
Exception handling is the process of responding to unwanted or unexpected events when a computer program runs.
The Try Catch statements allows you to define a block of code to be tested for exceptions (errors) while it is being executed.
The finally block is always executed no matter whether there is an exception or not.
'Programming > Java' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
23 Annotation (1) | 2024.01.21 |
---|---|
22 throw & throws (0) | 2024.01.21 |
20 Exceptions (0) | 2024.01.21 |
19 Interface (0) | 2024.01.20 |
18 Polymorphism (0) | 2024.01.20 |
λκΈ