에러 - 프로그램 코드에 의해서 수습될 수 없는 심각한 오류
예외 - 프로그램 코드에 의해서 수습될 수 있는 다소 미약한 오류
Exception클래스들 - 사용자의 실수와 같은 외적인 요인에 의해 발생하는 예외
- 발생할 가능성이 있는 문장들에 대해 예외처리를 해주지 않으면 컴파일조차 안됨
RuntimeException클래스들 - 프로그래머의 실수로 발생하는 예외
- 예외처리를 하지않아도 실행됨(예외발생)
RuntimeException클래스는 Exception클래스의 하위클래스
예외처리
정의 - 프로그램 실행 시 발생할 수 있는 예외에 대비한 코드를 작성하는 것
목적 - 프로그램의 비정상 종료를 막고, 정상적인 실행상태를 유지하는 것
예외를 처리하지 못하면 프로그램은 비정상적으로 종료
예외 처리위해 try-catch문 사용
|
1
2
3
4
5
6
7
8
9
|
try {
// 예외가 발생할 가능성이 있는 문장
} catch (Exception1 e1) {
// Exception1이 발생했을 경우, 이를 처리하기 위한 문장
} catch (Exception2 e2) {
// Exception2이 발생했을 경우, 이를 처리하기 위한 문장
} catch (ExceptionN eN) {
// ExceptionN이 발생했을 경우, 이를 처리하기 위한 문장
}
|
cs |
예시
- 예외처리 없는 경우
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
public class ExceptionEx2 {
public static void main(String[] args) {
int number = 100;
int result = 0;
for(int i=0; i<10; i++) {
result = number / (int)(Math.random() * 10);
System.out.println(result);
}
}
}
|
cs |
출력
12
Exception in thread "main" java.lang.ArithmeticException: / by zero
at exception.ExceptionEx2.main(ExceptionEx2.java:8)
--> 0으로 나눠서 예외 발생!
- 예외처리 적용
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
public class ExceptionEx2 {
public static void main(String[] args) {
int number = 100;
int result = 0;
for(int i=0; i<10; i++) {
try {
result = number / (int)(Math.random() * 10);
System.out.println(result);
} catch(ArithmeticException e) { // 예외가 발생하면 처리하는 코드
System.out.println("0");
}
}
}
}
|
cs |
출력
50
100
0
11
100
20
12
11
12
12
--> 예외 처리
예외정보 처리 방법
예외가 발생했을 때 생성되는 예외 클래스의 인스턴스에는 발생한 예외에 대한 정보가 담겨 있음
printStackTrace() - 예외발생 당시의 호출스택(Call Stack)에 있었던 메소드의 정보와 예외 메시지 화면에 출력
getMessage() - 발생한 예외클래스의 인스턴스에 저장된 메시지를 얻을 수 있음
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
public class ExceptionEx8 {
public static void main(String[] args) {
System.out.println(1);
System.out.println(2);
try {
System.out.println(3);
System.out.println(0/0); // 예외발생!
System.out.println(4);
} catch(ArithmeticException ae) {
ae.printStackTrace();
System.out.println("예외메시지 : " + ae.getMessage());
}
System.out.println(6);
}
}
|
cs |
출력
1
2
3
java.lang.ArithmeticException: / by zero
at exception.ExceptionEx8.main(ExceptionEx8.java:8)
예외메시지 : / by zero
6
예외 발생시키기
키워드 throw를 사용해서 고의로 예외 발생시킬 수 있음
1. 먼저 연산자 new를 이용해서 발생시키려는 예외 클래스의 객체를 만듦
ex. Exception e = new Exception("고의로 발생시켰음");
2. 키워드 throw를 이용해서 예외 발생시킴
throw e;
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
package exception;
public class ExceptionEx9 {
public static void main(String[] args) {
try {
Exception e = new Exception("고의로 발생시켰음");
throw e;
// throw new Exception("고의로 발생시켰음"); // 한줄로 작성가능
} catch(Exception e) {
System.out.println("에러 메세지 : " + e.getMessage());
e.printStackTrace();
}
System.out.println("프로그램이 정상 졸료");
}
}
|
cs |
출력
에러 메세지 : 고의로 발생시켰음
java.lang.Exception: 고의로 발생시켰음
프로그램이 정상 종료
at exception.ExceptionEx9.main(ExceptionEx9.java:7)
메소드에 예외 선언하기
try-catch문 사용하는 것 외에,
예외를 메소드에 선언하는 방법이 있다
메소드에 예외를 선언하려면,
메소드의 선언부에 키워드 throws를 사용해서 메소드 내에서 발생할 수 있는 예외를 적어주면 됨
|
1
2
3
|
void method() throws Exception1, Exception2, ... ExceptionN {
// 메소드 내용
}
|
cs |
메소드 내에서 발생할 가능성이 있는 예외를 메소드의 선언부에 명시하여,
이 메소드를 사용(호출)하는 쪽에서 이에 대한 처리를 하도록 함
-> 예외가 발생할 가능성이 있는 메소드를 호출한 메소드에게 예외를 전달하여 예외처리를 맡기는 것
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
public class ExceptionEx12 {
public static void main(String[] args) throws Exception {
method1();
}
static void method1() throws Exception {
method2();
}
static void method2() throws Exception {
throw new Exception(); // 예외 발생시킴!
}
}
|
cs |
출력
Exception in thread "main" java.lang.Exception
at exception.ExceptionEx12.method(ExceptionEx12.java:12)
at exception.ExceptionEx12.method(ExceptionEx12.java:8)
at exception.ExceptionEx12.method(ExceptionEx12.java:4)
method2()에서 'throw new Exception();'문장에 의해 예외 발생!
try-catch문으로 예외처리를 하지 않았으므로 method2()를 호출한 method1()로 예외를 넘김
method1()에서도 예외처리를 하지 않았으므로 main메소드로 예외를 넘김
main메소드에서도 예외처리를 하지 않았으므로 비정상적으로 종료
- 예외가 발생한 메소드에서 예외처리
(1)
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
public class ExceptionEx13 {
public static void main(String[] args) {
method1();
}
static void method1() {
// 발생한 예외를 바로 처리
try {
throw new Exception(); // 예외 발생!
} catch(Exception e) {
System.out.println("method1메소드에서 예외 처리!");
e.printStackTrace();
}
}
}
|
cs |
출력
method1메소드에서 예외 처리!
java.lang.Exception
at exception.ExceptionEx13.method1(ExceptionEx13.java:9)
at exception.ExceptionEx13.main(ExceptionEx13.java:3)
(2)
|
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
|
package exception;
import java.io.File;
public class ExceptionEx15 {
public static void main(String[] args) {
File f = createFile(args[0]);
System.out.println(f.getName() + " 파일이 성공적으로 생성되었습니다.");
}
static File createFile(String fileName) {
// 예외가 발생한 메소드에서 예외 처리!
try {
if(fileName==null || fileName.equals(""))
throw new Exception("파일이름이 유효하지 않습니다."); // 예외 발생!
} catch(Exception e) {
fileName = "제목없음.txt";
} finally { // 예외가 발생하든 안하든 무조건 실행되는 구문
File f = new File(fileName);
createNewFile(f);
return f;
}
}
static void createNewFile(File f) {
try {
f.createNewFile();
} catch(Exception e) { }
}
}
|
cs |
출력
""를 입력했을 때 -> 제목없음.txt 파일이 성공적으로 생성되었습니다.
next.txt를 입력했을 때 -> next.txt파일이 성공적으로 생성되었습니다.
- 예외가 선언된 메소드를 호출한 메소드에서 예외처리
(1)
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
package exception;
public class ExceptionEx14 {
public static void main(String[] args) {
// Exception예외가 선언된 method1()메소드를 호출한 메소드에서 예외 처리!
try {
method1();
} catch(Exception e) {
System.out.println("main메소드에서 예외 처리");
e.printStackTrace();
}
}
static void method1() throws Exception {
throw new Exception(); // 예외 발생!
}
}
|
cs |
출력
main메소드에서 예외 처리
java.lang.Exception
at exception.ExceptionEx14.method1(ExceptionEx14.java:15)
at exception.ExceptionEx14.main(ExceptionEx14.java:7)
(2)
|
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
|
package exception;
import java.io.File;
public class ExceptionEx16 {
public static void main(String[] args) {
// 예외가 선언된 메소드를 호출한 메소드에서 예외를 처리!
try {
File f = createFile(args[0]);
System.out.println(f.getName() + "파일이 성공적으로 생성되었습니다.");
} catch(Exception e) {
System.out.println(e.getMessage() + " 다시 입력해 주시기 바랍니다.");
}
}
static File createFile(String fileName) throws Exception { // 메소드에 예외선언
if(fileName==null || fileName.equals(""))
// 예외 발생 -> 이 메소드(createFile())를 호출한 메소드(main())가 예외를 처리하도록 함
throw new Exception("파일이름이 유효하지 않습니다.");
File f = new File(fileName);
f.createNewFile(); // 이 이름의 파일이 존재하지 않으면 파일 생성
return f;
}
}
|
cs |
'아카이브 > 자바의 정석' 카테고리의 다른 글
| 9장 java.lang패키지와 유용한 클래스 20201014 (0) | 2020.10.14 |
|---|---|
| 8장 예외처리 20201012 (0) | 2020.10.12 |
| 7장 20200926 (0) | 2020.09.26 |
| 7장 20200925 (0) | 2020.09.25 |
| 7장 20200924 (0) | 2020.09.24 |