์ฌ๋ฌ ์์ธ๋ฅผ ํฌ์ฐฉํ๋ ๋ฐฉ๋ฒ์ ๋ฐฐ์ฐ๊ธฐ ์ ์ Java์ ๊ธฐ๋ณธ ์์ธ ์ฒ๋ฆฌ ์ ๋ํด ์ ์๊ณ ์์ด์ผ ํฉ๋๋ค . ์์ผ๋ก๋ Java์ try ๋ฐ catch ๋ธ๋ก์ ์ต์ํ๋ค๊ณ ๊ฐ์ ํฉ๋๋ค.
Java์์ ์ฌ๋ฌ catch ๋ธ๋ก์ด ํ์ํ ์ด์ ๋ ๋ฌด์์ ๋๊น?
Java์ ์ฌ๋ฌ catch ๋ธ๋ก์ ๋ค์ํ ์ ํ์ ์์ธ๋ฅผ ์ฒ๋ฆฌํ๋ ๋ฐ ์ฌ์ฉ๋ฉ๋๋ค. Java 7์ด ์ถ์๋๊ธฐ ์ ์ ํน์ ์์ธ๋ฅผ ํฌ์ฐฉํ๋ ค๋ฉด ํน์ catch ๋ธ๋ก์ด ํ์ํ์ต๋๋ค. ์ด๋ก ์ธํด ์ค๋ณต ์ฝ๋ ๋ธ๋ก์ด ์์ฑ๋์ด ๋นํจ์จ์ ์ธ ์ ๊ทผ ๋ฐฉ์์ด ๋์์ต๋๋ค. ์กํ ์์ธ๋ฅผ ํ์ธํ๋ ค๋ฉด ๋ค์ ์๋ฅผ ์ดํด๋ณด์ญ์์ค. ๋ค๋ฅธ ์ข ๋ฅ์ ์์ธ์ ๋ํด ๋ณ๋์ catch ๋ธ๋ก์ ์ฌ์ฉํฉ๋๋ค.๋ณ๋์ Catch ๋ธ๋ก์ ์ฌ์ฉํ๋ ์
import java.util.Arrays;
public class ExceptionHandler {
public static void main(String[] args) {
Integer[] colorsOfASpectrum = { 7, 6, 5, 4, 3, 2, 1, 0 };
try {
System.out.println("Total number of options on a dice are: " + Arrays.toString(colorsOfASpectrum));
// un-comment the following line to see "Index Out of Bounds Exception"
// colorsOfASpectrum[10] = 7; // Index Out of Bounds Exception
System.out.println(colorsOfASpectrum[0] / 0); // Arithmetic Exception
} catch (ArrayIndexOutOfBoundsException e) {
// This catch block executes in case of "Index Out of Bounds Exception"
System.out.println("Array Index Out Of Bounds Exception " + e);
} catch (ArithmeticException e) {
// This catch block executes in case of "Arithmetic Exception"
System.out.println("Arithmetic Exception " + e);
}
System.out.println("\n----Rest of the code executes here----");
}
}
์ฐ์ถ
์คํํธ๋ผ์ ์ด ์์์ ๋ค์๊ณผ ๊ฐ์ต๋๋ค. [7, 6, 5, 4, 3, 2, 1] ์์ธ ๋ฐ์ java.lang.ArithmeticException: / by zero ----๋๋จธ์ง ์ฝ๋๋ ์ฌ๊ธฐ์์ ์คํ๋ฉ๋๋ค----
๋ณด์๋ค์ํผ ์์ ์์์ ์์ธ๊ฐ ๋ฐ์ํ๋ฉด ๋ค๋ฅธ ๋ธ๋ก์ด ์คํ๋ฉ๋๋ค. ๋ค๋ฅธ ์ ํ์ ์์ธ๋ฅผ ํฌ์ฐฉํ๊ธฐ ์ํด ๋์ผํ ์ฝ๋ ๋ธ๋ก์ ์ฌ์ฉํ์ฌ ์ฌ๋ฌ ์์ธ๋ฅผ ํฌ์ฐฉํ๋ ๋ณด๋ค ํจ์จ์ ์ธ ๋ฐฉ๋ฒ์ด ์์ต๋๋ค. ๋ค์ ์๋ฅผ ์ดํด๋ณด์ญ์์ค.
Java์์ ๋ค์ค Catch ๋ธ๋ก์ ์ฌ์ฉํ๋ ์
import java.util.Arrays;
public class MultiExceptionHandler {
public static void main(String[] args) {
Integer[] colorsOfASpectrum = { 7, 6, 5, 4, 3, 2, 1 };
try {
System.out.println("Total colors on a spectrum are: " + Arrays.toString(colorsOfASpectrum));
// colorsOfASpectrum[10] = 7; // Index Out of Bounds Exception
System.out.println(colorsOfASpectrum[0] / 0); // Arithmetic Exception
} catch (ArrayIndexOutOfBoundsException | ArithmeticException e) {
// We don't need two different catch blocks for different kinds of exceptions
// Both exceptions will be handled using this multiple catch block
System.out.println("Exception Encountered " + e);
}
System.out.println("\n----Rest of the code executes here----");
}
}
์ฐ์ถ
๋ค๋ฅธ ์ข ๋ฅ์ ์์ธ๋ฅผ ์ถ๋ ฅํ๊ธฐ ์ํด 13ํ์ ์ฃผ์์ ํด์ ํ ์ ์์ต๋๋ค.
์คํํธ๋ผ์ ์ด ์์์ ๋ค์๊ณผ ๊ฐ์ต๋๋ค. [7, 6, 5, 4, 3, 2, 1] ์์ธ ๋ฐ์ java.lang.ArithmeticException: / by zero ----๋๋จธ์ง ์ฝ๋๋ ์ฌ๊ธฐ์์ ์คํ๋ฉ๋๋ค----
GO TO FULL VERSION