hyeonga_code
Java_55_타입 추론, var 본문
- Exception
- 프로그램 소스 오류가 아닌 프로그램 실행 시 발생할 수 있는 오류
- 예외 처리
- 예외가 발생을 알려주는 것
- 예외 처리 방법
- 강제 예외
throw
- 예외 전가
- 미뤄버림(main에 있으면 system으로 넘김> 처리 X, 에러 발생)
throws
- 예외 처리
try ~ catch
- 예외 클래스 만들기
1. Exception 클래스 상속
2. public String getMessage() 메소드 오버라이드
- 오류
- 컴파일 에러 : Compile 과정 중에 발생
- 런타임 에러 : 실행 중에 발생
- 에러 : 프로그램 코드에 의해 수습될 수 없는 심각한 오류
- 예외 : 프로그램 코드에 의해 수습될 수 있는 미약한 오류
- 오류가 발생했을 경우 오류를 잡을 수 있는 단계까지 메소드 단위로 상위로 올라가게 됩니다.
- Exception handling_예외처리
- 프로그램 실행 시 발생할 수 있는 예외의 발생에 대비한 코드를 작성합니다.
- 프로그램의 비정상적인 종료를 방지합니다.
- 정상적인 실행 상태를 유지합니다.
- try-catch
try{
// 예외로 발생할 가능성이 있는 코드
} catch (Exception '예외 1'){
'예외 1'이 발생했을 경우 처리하기 위한 코드
} catch (Exception '예외 2'){
'예외 2'가 발생했을 경우 처리하기 위한 코드
}
- 해설 순서
- try Scopep 내에서 예외가 발생했는지 확인합니다.
- 발생한 예외와 일치하는 catch Scope가 있는지 확인합니다.
- 일치하는 catch 가 있다면 수행하고 try-catch 문을 빠져나가고 다음 코드들을 실행합니다.
- 일치하는 catch 를 찾지 못한 경우
'adv.exception_ex' 패키지 생성
'ExceptionEx.java' 클래스 생성
=====
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
|
package adv.exception_ex;
// 예외
public class ExceptionEx {
// 나누기 함수 생성
static int divide(int a, int b) {
return a/b;
}
public static void main(String[] args) {
// 정상 작동
int result = divide(4,2);
System.out.println("4/2 = " + result);
/* 4 / 2 = 2 */
// 오류 발생
/*
result = divide(4,0);
System.out.println("4/0 = " + result);
- 오류
Exception in thread "main" java.lang.ArithmeticException: / by zero
at labs/adv.exception_ex.ExceptionEx.divide(ExceptionEx.java:8)
- divide() 함수에서 오류가 발생했습니다.
at labs/adv.exception_ex.ExceptionEx.main(ExceptionEx.java:19)
- 오류가 발생하여 main()으로 넘어와 오류로 처리되었습니다.
System.out.println("End program"); // 오류가 발생하면 중지되어 실행되지 않습니다.
*/
// 예외처리
try {
result = divide(4,0);
System.out.println("4/0 = " + result);
} catch(ArithmeticException ex) { // 실행 중 문제가 발생한 경우 실행하겠습니다.
System.out.println("Error[ " + ex.getMessage() + " ]");
}
/* Error[ / by zero ] */
// 다중 예외 처리
try {
char[] a = new char[3];
a[5] = 1;
/*
- 오류
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
Index 5 out of bounds for length 3
at labs/adv.exception_ex.ExceptionEx.main(ExceptionEx.java:44)
*/
result = divide(4,0);
System.out.println("4/0 = " + result);
} catch(ArithmeticException ex) { // 실행 중 문제가 발생한 경우 실행하겠습니다.
System.out.println("Error[ " + ex.getMessage() + " ]");
} catch(ArrayIndexOutOfBoundsException ex) {
System.out.println("Error[ " + ex.getMessage() + " ]");
}
/*
Error[ Index 5 out of bounds for length 3 ]
*/
}
}
|
- 모든 오류에 대해 예외 처리를 할 수 있습니다.
- 최상위 예외 분류를 예외처리하여 간단하게 작성합니다.
=====
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
|
package adv.exception_ex;
// 예외
public class ExceptionEx {
// 나누기 함수 생성
static int divide(int a, int b) {
return a/b;
}
public static void main(String[] args) {
// 정상 작동
int result = divide(4,2);
System.out.println("4/2 = " + result);
/* 4 / 2 = 2 */
// 오류 발생
/*
result = divide(4,0);
System.out.println("4/0 = " + result);
- 오류
Exception in thread "main" java.lang.ArithmeticException: / by zero
at labs/adv.exception_ex.ExceptionEx.divide(ExceptionEx.java:8)
- divide() 함수에서 오류가 발생했습니다.
at labs/adv.exception_ex.ExceptionEx.main(ExceptionEx.java:19)
- 오류가 발생하여 main()으로 넘어와 오류로 처리되었습니다.
System.out.println("End program"); // 오류가 발생하면 중지되어 실행되지 않습니다.
*/
// 예외처리
try {
result = divide(4,0);
System.out.println("4/0 = " + result);
} catch(ArithmeticException ex) { // 실행 중 문제가 발생한 경우 실행하겠습니다.
System.out.println("Error[ " + ex.getMessage() + " ]");
}
/* Error[ / by zero ] */
// 다중 예외 처리
try {
char[] a = new char[3];
a[5] = 1;
/*
- 오류
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
Index 5 out of bounds for length 3
at labs/adv.exception_ex.ExceptionEx.main(ExceptionEx.java:44)
*/
result = divide(4,0);
System.out.println("4/0 = " + result);
} catch(ArithmeticException ex) { // 실행 중 문제가 발생한 경우 실행하겠습니다.
System.out.println("Error[ " + ex.getMessage() + " ]");
} catch(ArrayIndexOutOfBoundsException ex) {
System.out.println("Error[ " + ex.getMessage() + " ]");
}
/*
Error[ Index 5 out of bounds for length 3 ]
*/
// 최상위 예외 처리
try {
char[] a = new char[3];
a[5] = 1;
result = divide(4,0);
System.out.println("4/0 = " + result);
} catch(Exception e) { // 최상위 예외입니다.
System.out.println("Error");
}
/* Error */
}
}
|
- 사실 메소드를 이런식으로 작성하면 안됩니다.
=====
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
package adv.exception_ex;
// 예외
public class ExceptionEx {
// 나누기 함수 생성
static int divide(int a, int b) {
return a/b;
}
// 예외처리를 추가한 나누기 함수 생성
static int divide2(int a, int b) {
int result =0;
try {
result = a / b;
} catch(Exception e) {
System.out.println("Error");
}
return result;
}
public static void main(String[] args) {
// 정상 작동
int result = divide(4,2);
System.out.println("4/2 = " + result);
/* 4 / 2 = 2 */
result = divide2(4,2);
System.out.println("4/2 = " + result);
/* 4/2 = 2 */
result = divide2(4,0);
System.out.println("4/0 = " + result);
/* Error */
}
}
|
- 무슨 오류가 발생했는지 확인할 수 없습니다.
- 오류 메세지를 두 방법으로 출력합니다.
- 사용자에게 보여지는 메세지
- 개발자에세 보여지는 로그 메세지
=====
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
import java.util.*;
public class ex0325 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Input Count: ");
int su = in.nextInt();
/*
Input Count: A
// 엉뚱한 값을 넣었을 경우
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at ex0325.main(ex0325.java:8)
*/
}
}
|
- throws
=====
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
import java.util.*;
public class ex0325 {
public static void main(String[] args) throws InputMismatchException {
// 예외 처리를 전가
Scanner in = new Scanner(System.in);
System.out.print("Input Count: ");
int su = in.nextInt();
/*
Input Count: A
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at ex0325.main(ex0325.java:8)
*/
// 동일하게 나옴
}
}
|
- 예외 처리
=====
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
import java.util.*;
public class ex0325 {
public static void main(String[] args) {
try {
// 시도해 볼 것
Scanner in = new Scanner(System.in);
System.out.print("Input Count: ");
int su = in.nextInt();
}
catch (InputMismatchException e) {
// 에러가 발생했을 경우 처리할 값
System.out.println("Input Number!");
}
/*
Input Count: A
Input Number!
*/
// 메세지 발생
}
}
|
=====
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
import java.util.*;
public class ex0325 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while(true) {
try {
System.out.print("Input Count 1: ");
int su1 = in.nextInt();
System.out.print("Input Count 2: ");
int su2 = in.nextInt();
int res = su1 / su2;
System.out.println("Result : " + res);
break;
}catch(InputMismatchException e) {
System.out.println("Input Number!");
in.nextLine();
// 엔터를 칠 때까지 데이터를 유지
// 엔터 이후에는 데이터를 삭제하여 비어있는 변수 값부터 다시 반복
}catch (ArithmeticException e) {
// 오류 메세지가 뜰 경우
System.out.println("Can't div 0!");
// 원하는 메세지 출력하게 작성
}
}
/*
Input Count 1: A
Input Number!
Input Count 1: 6
Input Count 2: 3
Result : 2
Input Count 1: 10
Input Count 2: 0
Can't div 0!
*/
}
}
|
- 예외클래스 작성
=====
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
import java.util.*;
class MyException extends Exception {
// 상속을 받아야 예외 클래스임을 인정
private String message;
public MyException(String msg) {
super(msg);
}
@ Override
// 어노텐션 : 길잡이
// Override를 입력할 경우 getMessage()이름 정확하게 작성해야 함
public String getMessage() {
message = super.getMessage() + " : Exception class";
return message;
}
}
public class ex0325 {
public static void main(String[] args) {
try {
throw new MyException("Except Code");
}
catch (MyException e) {
System.out.println(e.getMessage());
}
/*
* Except Code : Exception class
*/
}
}
|
- 국어점수를 입력받고 0-100 사이가 아닐경우 에러메세지
=====
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
import java.util.*;
class MyException extends Exception{
/** 경고줄 뜨는 이유
* 시리얼 번호
* 어떤 예외인지 주석처리하는 부분
* private static final long serialVersionUID = 1L;
*/
private String message;
public MyException(String msg) {
// 작성하지 않아도 되는 코드
super(msg);
}
@Override
public String getMessage() {
// 필수 작성 코드
message = super.getMessage() + "Input from 0 to 100!";
return message;
}
}
public class ex0325 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
try {
System.out.print("Input Kor Score(from 0 to 100): ");
int kor = in.nextInt();
if (kor<0 || kor>100) {
throw new MyException("Error: ");
}
System.out.println("Kor : " + kor);
}catch(MyException e) {
System.out.println(e.getMessage());
}catch(Exception e) {
// 전부 캐치하지 못했을 경우
e.printStackTrace();
// 예외가 발생한 시점까지 사용된 모든 메소드를 반환
// 에러 위치 알 수 있음
}
}
}
|
'Java' 카테고리의 다른 글
Java_57_Log_로그 처리 (0) | 2023.10.17 |
---|---|
Java_56_예외 처리 (0) | 2023.10.16 |
Java_54_Lambda_람다식 (0) | 2023.10.15 |
Java_53_추상화 (0) | 2023.10.15 |
Java_52_extends, implements 의 차이 (0) | 2023.10.14 |