부스트코스 생활코딩 [쉽게 배우는 자바2] 공부 기록
끝
2022. 1. 13. ~ 2. 5.
1. 수업소개
Error vs Exception
숙명 vs 운명
2. 예외의 발생
package javaChapter2.javaChapter2_13;
public class ExceptionApp {
public static void main(String[] args) {
System.out.println(1);
System.out.println(2/0);
System.out.println(3);
}
}
자바에서 2를 0으로 나누는 것을 허용하지 않는다.
3. 예외의 처리
package javaChapter2.javaChapter2_13;
public class ExceptionApp {
public static void main(String[] args) {
System.out.println(1);
int[] scores = {10, 20, 30};
System.out.println(scores[0]); // 10
try {
System.out.println(scores[3]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("없는 값을 찾고 계시네요.");
}
try {
System.out.println(2 / 0);
} catch (ArithmeticException e) { // e는 변수
System.out.println("잘못된 계산이네요.");
}
System.out.println(3);
}
}
try ~ catch 구문의 사용법에 대해서 두루뭉술하게 알았었는데!
이 영상으로 어떤 때에 사용하는지 알 수 있었고, 필요에 따라 자주 사용할 수도 있을 것 같다.
package javaChapter2.javaChapter2_13;
public class ExceptionApp {
public static void main(String[] args) {
System.out.println(1);
int[] scores = {10, 20, 30};
System.out.println(scores[0]); // 10
try {
System.out.println(2);
System.out.println(scores[3]);
System.out.println(3);
System.out.println(2 / 0);
System.out.println(4);
} catch (ArithmeticException e) { // e는 변수
System.out.println("잘못된 계산이네요.");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("없는 값을 찾고 계시네요.");
}
System.out.println(5);
}
}
try 안에 있는 scores[3] 아래는 실행조차 되지 않는다!
4. 예외의 우선순위
package javaChapter2.javaChapter2_13;
public class ExceptionApp {
public static void main(String[] args) {
System.out.println(1);
int[] scores = {10, 20, 30};
System.out.println(scores[0]); // 10
try {
System.out.println(2);
// System.out.println(scores[3]);
System.out.println(3);
System.out.println(2 / 0);
System.out.println(4);
} catch (Exception e) {
System.out.println("뭔가 이상합니다. 오류가 발생했습니다.");
}
System.out.println(5);
}
}
예외는 상속이라는 것을 통해서 부모, 자시 관계가 있다.
부모 예외를 가져다 놓게 되면, 저 부모의 자식에 해당되는 어떤 예외가 발생하건 부모 exception이 처리한다.
5. e의 비밀
e는 변수.
e말고 다른 이름으로 해도되지만, 관념적으로 e를 쓰는 듯.
package javaChapter2.javaChapter2_13;
public class ExceptionApp {
public static void main(String[] args) {
System.out.println(1);
int[] scores = {10, 20, 30};
System.out.println(scores[0]); // 10
try {
System.out.println(2);
// System.out.println(scores[3]);
System.out.println(3);
System.out.println(2 / 0);
System.out.println(4);
} catch (ArithmeticException e) {
System.out.println("계산이 잘못된 것 같아요. " + e.getMessage()); // getMessage() <- error 원인 보여줌
e.printStackTrace(); // error message 보여줌
} catch (Exception e) { //e는 변수 Exception은 type
System.out.println("뭔가 이상합니다. 오류가 발생했습니다.");
}
System.out.println(5);
}
}
e.printStackTrace() 의 에러 메시지 내용은 창 맨 아래에 나타나는 것 같다.
6. Checked exception vs Unchecked exception
error는 어쩔 수 없는 것.
exception은 내가 잘 하면 해결할 수 있는 것
exception은 2개로 나눌 수 있다.
checked exception vs unchecked exception
checked exception => IOException (input output)
package javaChapter2.javaChapter2_13;
import java.io.FileWriter;
import java.io.IOException;
public class CheckedExceptionApp {
public static void main(String[] args) {
FileWriter f = null;
try {
f = new FileWriter("date3.txt");
f.write("Hello");
f.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
checked exception의 경우에는 반드시 try~catch나 throws를 통해 예외에 대해 조치를 해야 한다.
무심코 조치를 안 하고 넘어가는 것을 용인하지 않는다.
밑줄 같은 게 생겨서, 에러가 있다는 것을 알려준다.
uncheched exception은 try~catch 등 조치를 하지 않아도 컴파일은 된다.
컴파일 했을 때 콘솔창에서 에러가 난다.
7. Finally와 Resource 다루기
package javaChapter2.javaChapter2_13;
import java.io.FileWriter;
import java.io.IOException;
public class CheckedExceptionApp {
public static void main(String[] args) {
FileWriter f = null;
try {
f = new FileWriter("date3.txt");
f.write("Hello");
// close를 하기 전에 예외가 발생할 수 있기 때문에 finally로 처리해야 함
} catch (IOException e) {
e.printStackTrace();
} finally {
// 만약 f가 null 이 아니라면 close
if (f != null) {
try {
f.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
FileWriter try문 안에 f.close()를 담아버리면, 예외가 발생했을 때도 바로 catch문으로 넘어가버린다.
그러면 자원을 놓아줄 수가 없다.
이럴 때 finally를 배치해서 예외가 있든, 없든 자원을 놓아줄 수가 있다.
다만 코드가 꽤 복잡,,,
더 쉬운 방법도 있다고 한다.
그것은 다음 강의에서!
8. Try with Resource
왼쪽에 있는 코드와 똑같은 코드.
왼쪽에 있는 코드보다 오른쪽에 있는 코드가 훨씬 보기 좋다.
package javaChapter2.javaChapter2_13;
import java.io.FileWriter;
import java.io.IOException;
//AutoCloseable을 가지고 있으면 TryWithResource를 사용할 수 있다
public class TryWithResource {
public static void main(String[] args) {
try (FileWriter f = new FileWriter("date3.txt")) {
f.write("Hello");
// f.close(); // close가 필요없어서 자동으로 회색으로 나옴
} catch (IOException e) {
e.printStackTrace();
}
}
}
9. 수업을 마치며
package javaChapter2.javaChapter2_13;
public class MyException {
public static void main(String[] args) {
throw new RuntimeException("무언가 문제가 생겼습니다");
}
}
package javaChapter2.javaChapter2_13;
import java.io.FileWriter;
import java.io.IOException;
public class ThrowException {
public static void main(String[] args) throws IOException {
FileWriter f = new FileWriter("data4.txt");
}
}
throws를 사용해서 사용하면 내가 try~catch 할 필요가 없고, 사용하는 사람이 처리.
남에게 미룬다~!
부스트코스를 통해 생활코딩 자바 강의를 다 들었다!!!
긴 여정이었다.
예전에도 한 번 봤었던 것 같은데, 그때보다 이해는 더 잘 되는 것 같다.
이고잉님 설명 정말 최고다.
어려운 부분도 이고잉 님 덕부에 이해가 쏙쏙!
다음 여정들도 잘 해나가야지.
'Language > JAVA' 카테고리의 다른 글
[JAVA] 컬렉션즈 프레임워크 1~9 ArrayList, HashSet, Map (0) | 2022.02.14 |
---|---|
[JAVA] 제네릭 1~5 Generic - Data Type (0) | 2022.02.13 |
[JAVA] 인터페이스 1~5 interface , 다형성 (0) | 2022.02.11 |
[JSP] 'Dynamic Web Project' 프로젝트 생성 (0) | 2022.02.10 |
[JAVA] 상속 1~6 Inheritance , overriding , overloading , super (0) | 2022.02.10 |