🐣생활코딩 강의🐣
Java 예외 - https://www.youtube.com/playlist?list=PLuHgQVnccGMCrFJLxpjhE0N5tvOVxJuVB
문제 상황 파악하기
public class Main {
public static void main(String[] args) {
System.out.println(1);
System.out.println(2/0); // 문제의 코드
System.out.println(3);
}
}
➡️ 예외 처리가 필요하다
Try - Catch 적용하기
public class Main {
public static void main(String[] args) {
System.out.println(1);
int[] scores = {10, 20, 30};
try { // exception
System.out.println(scores[3]);
System.out.println(2 / 0);
} catch(ArithmeticException e) { // 2/0 예외 처리
System.out.println("잘못된 계산입니다"+e.getMessage());
e.printStackTrace();
} catch(ArrayIndexOutOfBoundsException e) { // scores[3] 예외 처리
System.out.println("범위를 벗어났습니다"+e.getMessage());
e.printStackTrace();
}
System.out.println(3);
}
}
✔️ e.getMessage() : 어떤 에러인지 확인하기✔️ e.printStackTrace() : 에러 메세지 출력하기
✔️ 부모 Exception 이 자식 Exception (ex. ArithmeticException / ArrayIndexOutOfBoundsException) 을 포함하여 예외 처리가 가능하다 → catch(Exception e) 로 대체 가능
☑️ 변경된 코드
public class Main {
public static void main(String[] args) {
...
try { // exception
System.out.println(scores[3]);
System.out.println(2 / 0);
} catch(Exception e) { // 변경
System.out.println("오류가 발생했습니다");
}
...
}
}
Try - Catch - Finally 적용하기
· Exception : Checked Exception & Unchecked Exception
· Checked Exception : 예외 처리가 필수
· RunTimeException 을 제외한 나머지 Exception (ex. IOException) 은 모두 Checked Exception
· IOException : FileNotFoundException
☑️ 프로젝트 내 파일 생성하는 코드
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
FileWriter f = null;
try { // 필수적으로 예외 처리 필요
f = new FileWriter("data.txt");
f.write("Hello Exception!");
// close 하기 전 예외가 발생할 수 있기 때문에 finally 로 처리해야 한다
// f.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 파일 존재 여부 파악하기
if (f != null) {
try {
f.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Try with Resource Statements
☑️ 위의 Try - Catch - Finally 와 같은 동작을 수행하는 코드
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try (FileWriter f = new FileWriter("data.txt") {
f.write("Hello Exception!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
→ f.close() 가 사라졌다
ThrowException
· 예외 생성하기 : throws
· Java7 부터 사용 가능
☑️ 위의 Try - Catch - Finally / Try with Resource Statements 와 같은 동작을 수행하는 코드
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
FileWriter f = new FileWriter("./data.txt");
}
}
'Spring > JAVA' 카테고리의 다른 글
Java 객체 지향 프로그래밍 (2) | 2023.09.29 |
---|---|
Java Method (0) | 2023.09.28 |
앱 만들기 2 - 배당금 계산기 (제어문, 배열, 메소드, 클래스, 인스턴스) (0) | 2023.09.25 |
앱 만들기 1 - 배당금 계산기 (변수, 입력값) (0) | 2023.09.22 |
변수 (0) | 2023.09.21 |