예외처리
1. 개념
예외 발생할 것을 대비해서 프로그램에서 제어할 수 있도록 처리하는 개념
오류와는 다르며 프로그램 수행 도중에 발생할 수 있는 장애에 대한 대처
2. 특징
- try~catch~finally 구문으로 제어
- 예외 넘기기 위해 throws 사용
3. 예외처리 키워드
- try 블록 : 예외가 발생할 수 있는 코드 포함
- catch 블록 : try 블록 내에서 발생한 예외를 처리
- finally : 예외 발생 여부와 상관 없이 실행되어야 하는 코드를 포함
- throw : 프로그램에서 직접 예외를 발생시키기 위해 사용
- throws : 해당 메서드에서 처리하지 않고 호출자에게 예외 처리 위임
4. 예외처리 방식
try {
// 예외가 발생될만한 코드
}
catch(FileNotFoundException e) {
// FileNotFoundException이 발생했다면 실행
}
catch(IOE Exception e) {
// IOException이 발생하였다면 실행
}
catch(Exception e) {
// FileNotFoundException, IOException 외의 Exception 발생하면 실행
} finally {
// 예외에 상관없이 무조건 실브행
// 예외의 나머지 처리, 자원 해제 용도
}
5. 자주 사용되는 예외 클래스
종류 | 설명 |
NullPointerException | 객체를 생성하지 않고 참조할 경우 해당 객체를 참조할 수 없어서 발생 |
InderOutOfBoundsException | 배열에서 인덱스 범위를 초과했을 때 발생 |
NumberFormatException | 문자열을 숫자로 변환할 때 해당 문자가 숫자 형태가 아니라면 발생 |
ClassCastException | 허용되지 않은 타입으로 변환할 때 발생 |
IllegalArgumentException | 매개변수가 의도하지 않은 상황을 유발할 때 발생 |
ArithmeticException | 산술연산에 오류 있을 때 발생(예: 0으로 나눈 경우) |
6. 간단한 예시
public class ExceptionExample {
public static void main(Strig[] args) {
try {
int[] numbers = {1, 2, 3};
System.out.println(numbers[3]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("배열의 범위를 벗어난 접근입니다.");
} finally {
System.out.println("이 코드는 항상 실행됩니다.");
}
}
}
예외처리 문제1
class ExceptionExample {
public static void p() throws Exception {
try {
System.out.println("A");
throw new Exception("");
} catch (Exception e) {
System.out.println("C");
throw e;
} finally {
System.out.println("D");
}
}
public static void main(String[] args) {
try {
System.out.println("A-1");
p();
System.out.println("B-1");
} catch (Exception e) {
System.out.println("C-1");
} finally {
System.out.print("D-1");
}
}
}
출력결과
A-1
A
C
D
C-1
D-1
예외처리 문제2
class ExceptionExample {
public static void p() throws Exception {
try {
System.out.println("A");
throw new Exception("");
} catch (Exception e) {
System.out.println("C");
} finally {
System.out.println("D");
}
}
public static void main(String[] args) {
try {
System.out.print("A-1");
p();
System.out.println("B-1");
} catch (Exception e) {
System.out.println("C-1");
} finally {
System.out.println("D-1");
}
}
}
출력 결과
A-1
A
C
D
B-1
D-1
예외처리 문제3
class ExceptionTest {
ExceptionTest() {
try {
method();
System.out.print("A");
} catch(Exception e) {
System.out.print("B");
} finally {
System.out.print("C");
}
System.out.println("D");
}
void method() throws Exception {
throw new Exception();
}
public static void main(String[] args) {
ExceptionTest t = new ExceptionTest();
}
}
출력 결과
B C D
예외처리 문제4
class TextException {
public static void main(String[] args) {
try {
System.out.println("문장 A");
foo();
System.out.println("문장 B");
} catch(Exception e) {
System.out.println("문장 C");
}
System.out.println("문장 D");
}
public static void foo() throws Exception {
try {
System.out.println("문장 E");
throw new Exception();
} catch (Exception e) {
System.out.println("문장 F");
throw e;
} finally {
System.out.println("문장 G");
}
}
}
출력 결과
문장 A
문장 E
문장 F
문장 G
문장 C
문장 D
예외처리 문제5
class TextException {
public static void main(String[] args) {
try {
System.out.print("A");
foo();
System.out.print("B"); // This will not execute because foo() throws an exception
} catch (Exception e) {
System.out.print("C");
} finally {
System.out.println("E");
}
}
public static void foo() throws Exception {
try {
System.out.print("F");
throw new Exception();
} catch (Exception e) {
System.out.print("G");
} finally {
System.out.print("H");
}
}
}
출력 결과
AFGHBD
E
'ETC > 정보처리기사' 카테고리의 다른 글
[Java] 메서드 오버로딩 / 오버라이딩 / 하이딩 (2) | 2024.10.23 |
---|---|
[Java] 정보처리기사 자바의 상속 & 생성자 (3) | 2024.10.23 |
[Java] 정보처리기사 추상클래스 / 인터페이스 정리 (오류 발생 문제 풀이) (3) | 2024.10.18 |
[Python] 파이썬 학습노트3 - 문제풀이, 슬라이싱, lambda(람다) (2) | 2024.10.16 |
[Python] 파이썬 학습노트2 -자료구조(리스트, 튜플, 셋, 딕셔너리) (3) | 2024.10.16 |
예외처리
1. 개념
예외 발생할 것을 대비해서 프로그램에서 제어할 수 있도록 처리하는 개념
오류와는 다르며 프로그램 수행 도중에 발생할 수 있는 장애에 대한 대처
2. 특징
- try~catch~finally 구문으로 제어
- 예외 넘기기 위해 throws 사용
3. 예외처리 키워드
- try 블록 : 예외가 발생할 수 있는 코드 포함
- catch 블록 : try 블록 내에서 발생한 예외를 처리
- finally : 예외 발생 여부와 상관 없이 실행되어야 하는 코드를 포함
- throw : 프로그램에서 직접 예외를 발생시키기 위해 사용
- throws : 해당 메서드에서 처리하지 않고 호출자에게 예외 처리 위임
4. 예외처리 방식
try { // 예외가 발생될만한 코드 } catch(FileNotFoundException e) { // FileNotFoundException이 발생했다면 실행 } catch(IOE Exception e) { // IOException이 발생하였다면 실행 } catch(Exception e) { // FileNotFoundException, IOException 외의 Exception 발생하면 실행 } finally { // 예외에 상관없이 무조건 실브행 // 예외의 나머지 처리, 자원 해제 용도 }
5. 자주 사용되는 예외 클래스
종류 | 설명 |
NullPointerException | 객체를 생성하지 않고 참조할 경우 해당 객체를 참조할 수 없어서 발생 |
InderOutOfBoundsException | 배열에서 인덱스 범위를 초과했을 때 발생 |
NumberFormatException | 문자열을 숫자로 변환할 때 해당 문자가 숫자 형태가 아니라면 발생 |
ClassCastException | 허용되지 않은 타입으로 변환할 때 발생 |
IllegalArgumentException | 매개변수가 의도하지 않은 상황을 유발할 때 발생 |
ArithmeticException | 산술연산에 오류 있을 때 발생(예: 0으로 나눈 경우) |
6. 간단한 예시
public class ExceptionExample { public static void main(Strig[] args) { try { int[] numbers = {1, 2, 3}; System.out.println(numbers[3]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("배열의 범위를 벗어난 접근입니다."); } finally { System.out.println("이 코드는 항상 실행됩니다."); } } }
예외처리 문제1
class ExceptionExample { public static void p() throws Exception { try { System.out.println("A"); throw new Exception(""); } catch (Exception e) { System.out.println("C"); throw e; } finally { System.out.println("D"); } } public static void main(String[] args) { try { System.out.println("A-1"); p(); System.out.println("B-1"); } catch (Exception e) { System.out.println("C-1"); } finally { System.out.print("D-1"); } } }
출력결과
A-1 A C D C-1 D-1
예외처리 문제2
class ExceptionExample { public static void p() throws Exception { try { System.out.println("A"); throw new Exception(""); } catch (Exception e) { System.out.println("C"); } finally { System.out.println("D"); } } public static void main(String[] args) { try { System.out.print("A-1"); p(); System.out.println("B-1"); } catch (Exception e) { System.out.println("C-1"); } finally { System.out.println("D-1"); } } }
출력 결과
A-1 A C D B-1 D-1
예외처리 문제3
class ExceptionTest { ExceptionTest() { try { method(); System.out.print("A"); } catch(Exception e) { System.out.print("B"); } finally { System.out.print("C"); } System.out.println("D"); } void method() throws Exception { throw new Exception(); } public static void main(String[] args) { ExceptionTest t = new ExceptionTest(); } }
출력 결과
B C D
예외처리 문제4
class TextException { public static void main(String[] args) { try { System.out.println("문장 A"); foo(); System.out.println("문장 B"); } catch(Exception e) { System.out.println("문장 C"); } System.out.println("문장 D"); } public static void foo() throws Exception { try { System.out.println("문장 E"); throw new Exception(); } catch (Exception e) { System.out.println("문장 F"); throw e; } finally { System.out.println("문장 G"); } } }
출력 결과
문장 A 문장 E 문장 F 문장 G 문장 C 문장 D
예외처리 문제5
class TextException { public static void main(String[] args) { try { System.out.print("A"); foo(); System.out.print("B"); // This will not execute because foo() throws an exception } catch (Exception e) { System.out.print("C"); } finally { System.out.println("E"); } } public static void foo() throws Exception { try { System.out.print("F"); throw new Exception(); } catch (Exception e) { System.out.print("G"); } finally { System.out.print("H"); } } }
출력 결과
AFGHBD E
'ETC > 정보처리기사' 카테고리의 다른 글
[Java] 메서드 오버로딩 / 오버라이딩 / 하이딩 (2) | 2024.10.23 |
---|---|
[Java] 정보처리기사 자바의 상속 & 생성자 (3) | 2024.10.23 |
[Java] 정보처리기사 추상클래스 / 인터페이스 정리 (오류 발생 문제 풀이) (3) | 2024.10.18 |
[Python] 파이썬 학습노트3 - 문제풀이, 슬라이싱, lambda(람다) (2) | 2024.10.16 |
[Python] 파이썬 학습노트2 -자료구조(리스트, 튜플, 셋, 딕셔너리) (3) | 2024.10.16 |