문법
try {
} catch(Exception e) {
}
예제
try {
System.out.println(3 / 0);
} catch (Exception e) {
System.out.println("문제 원인 : " + e.getMessage());
// e.printStackTrace();
}
getMessage()룰 통해서 오류 내용을 알 수 있다
index 크기보다 벗어나는 경우
try {
int[] arr = new int[3];
arr[5] = 0;
} catch (Exception e) {
System.out.println("문제 원인 : " + e.getMessage());
// e.printStackTrace();
}
printStackTrace()는 getMessage()와 비슷함
try {
int[] arr = new int[3];
arr[7] = 7;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("index 범위를 벗어났습니다");
} catch (Exception e) {
System.out.println("문제 원인 : " + e.getMessage());
e.printStackTrace();
}
index를 위에 있는 catch문부터 실행
try {
String s = null;
System.out.println(s.toLowerCase());
} catch (ArithmeticException e) {
System.out.println("잘못 계산했습니다");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("index 범위를 벗어났습니다");
} catch (ClassCastException e) {
System.out.println("잘못된 형변환입니다.");
} catch (Exception e) {
System.out.println("그 외의 문제 원인 : " + e.getMessage());
e.printStackTrace();
}
두개의 예외처리 합치기
try {
System.out.println(3 / 0);
} catch (ArithmeticException | ArrayIndexOutOfBoundsException e) {
System.out.println("실수");
} catch (ClassCastException e) {
System.out.println("잘못된 형변환입니다.");
} catch (Exception e) {
System.out.println("그 외의 문제 원인 : " + e.getMessage());
e.printStackTrace();
}
or를 통해서 두개의 예외를 합칠 수 있다
int age = 18;
try {
if (age < 19) {
throw new Exception("만 19세 미만에게는 판매하지 않습니다");
} else {
System.out.println("판매합니다");
}
} catch (Exception e) {
System.out.println("문제 원인 : " + e.getMessage());
e.printStackTrace();
}
try {
System.out.println("가게 문을 연다");
throw new Exception("오늘은 휴무");
} catch (Exception e) {
System.out.println("문제 원인 : " + e.getMessage());
e.printStackTrace();
} finally {
System.out.println("가게 문을 닫는다");
}
try 만 단독사용 불가능
try {
System.out.println(3 / 0);
} finally {
System.out.println("프로그램 종료");
}
e.getMessage() --> 예외 객체로 부터 예외 메세지를 갖고옴
e.printStackTrace --> 예외가 발생한 위치를 추적해 가면서 예외가 발생한 클래스명 행번호등 출력
class AgeLessThan19Exception extends Exception {
public AgeLessThan19Exception(String message) {
super(message);
}
}
public class _06_CustomException {
public static void main(String[] args) {
// 사용자 정의 예외
int age = 18;
try {
if (age < 19) {
throw new AgeLessThan19Exception("만 19세 미만에게는 판매하지 않습니다");
} else {
System.out.println("판매합니다");
}
} catch (AgeLessThan19Exception e) {
System.out.println("성인이 되어서 와라");
} catch (Exception e) {
System.out.println("모든 예외 처리");
}
System.out.println("프로그램 정상 종료");
System.out.println("----------------");
}
}
public class _07_Throws {
public static void main(String[] args) {
// 예외처리 미루기
try {
writeFile();
} catch (IOException e) {
e.printStackTrace();
System.out.println("main 메소드에서 해결");
}
}
// 메소드 내에서 처리하다가 발생한 문제를 내부적으로 처리하지 않고 다른데로 던진다.
public static void writeFile() throws IOException {
/*try {
FileWriter writer = new FileWriter("test.txt");
throw new IOException("파일 쓰기 실패");
} catch (IOException e) {
e.printStackTrace();
System.out.println("writeFile 메소드 내에서 자체 해결했어요");
}*/
FileWriter writer = new FileWriter("test.txt");
throw new IOException("파일 쓰기 실패");
}
}
참고
나도코딩 유튜브