예외처리_Java

miin·2021년 6월 4일
0

JAVA 

목록 보기
9/13

예외처리

정의
멈출 수 있는 예외상황을 미리 정의하여 예외가 발생하였을 때 프로그램이 멈추지 않도록 미리 정의해 놓는것을 의미

try{
//예외 발생 가능한 지점
} catch(처리할예외클래스 변수명) {
//예외처리할 내용
} catch (예외처리할클래스 변수명) {
//처리할 내용
}finally {
//예외가 발생하든 하지않든 반드시 실행되어야 할 코드를 기술한다
}
public static void main(String[] args) {
try {
int num = integer.parseInt("안녕");
System.out.println("정상 동작시만 출력");
} catch (NumberFormatException e) {
System.out.println(e);
e.printStackTrace();
} catch (Exception e) {
System.out.println(e);
e.printStackTrace();
} finally {
System.out.println("예외 관계없이 항상 출력");
}
}
//배열
int []arr = {1,2,3,4,5};
int index = 10;
java.util.Scanner sc = new java.util.Scanner(System.in);
while(true) {
try{
System.out.println("출력하고싶은 배열의 인덱스를 입력");
index = Integer.parseInt(sc.nextLine());
System.out.println(arr[index]);
break;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("잘못된 인덱스를 입력하였습니다");
} catch (NumberFormatException e) {
System.out.println("숫자를 입력하였습니다");
} catch (Exception e) {//e.printStackTrace();
System.out.println("알수없는 예외 발생");
}
}

//throw문 사용 예외
throw와 throws의 차이점을 명확하게 알고 있어야함
throw 원하는 예외를 강제로 생성할 수 있다
throws 호출한 사람이 예외처리하라고 하는것
try {
//throw new Exception();
throw new NumberFormatException();
} catch (NumberFormatException e) {
System.out.println(e);
e.printStackTrace();
} catch (Exception e) {
System.out.println(e);
e.printStackTrace();
} finally {
System.out.println("예외 관계없이 항상 출력");
}

System.out.println(e); 예외내용을 문자열로 찍으라는 의미
e.printStackTrace(); 예외 내용뿐 아니라 예외가 발생한 함수들의 호출관계를 모두 찍음
Exception class : 모든 예외를 한번에 처리하는 클래스 (맨 마지막에 기술)
디폴트 생성자: () {}
생성자 추가: 오른쪽 마우스-> source -> Generate constructor using fields
세터게터추가: 오른쪽 마우스 -> soure->setter getter

0개의 댓글