발생한 예외와 일치하는 catch 블럭으로 이동
일치하는 catch 블럭 내 문장을 수행하고 try-catch 문을 나와 프로그램 진행
catch 블럭을 건너뛰어서 진행
Scanner sc = new Scanner(System.in);
System.out.print("정수를 입력하세요 => ");
try{
int inputNum = sc.nextInt(0;
sc.nextLine();
System.out.println("입력한 정수 : " + inputNum);
} catch(InputMismatchException e) { // InputMismatchException : 정수를 입력해야 하는데 문자를 입력한 경우 예외 발생
System.out.println(">> 경고 : 정수만 입력하세요!! <<");
e.printStackTrace(); // 오류 주소 출력
}
sc.close();
InputMismatchException
정수를 입력해야 하는데 문자를 입력
ArithmeticException
정수를 0으로 나눈 경우
NullPointerException
null reference 를 참조한 경우
ArrayIndexOutOfBoundException
배열의 범위를 벗어나서 접근
FileNotFoundException
파일을 찾을 수 없는 경우
NumberFormatException
문자를 숫자로 변환하는 경우
ClassNotFoundException
클래스 로딩에 실패한 경우
e.printStackTrace() : 에러위치를 알려준다.
e.getMessage : 에러 입력값을 알려준다.
try{
System.out.print("국어 : ");
byte kor = Byte.parseByte(sc.nextLine());
if(!sj.check_jumsu(kor)){
sc.close();
return; // return 을 만나면 해당 메소드는 종료된다.
}
else{
sj.kor = kor;
} catch(NumberFormatException e) {
e.printStackTrace() // 에러위치 알려줌.
System.out.println(e.getMessage); // 에러 입력값 알려줌
}
String input_str = "";
try{
System.out.print("국어 : ");
input_str = sc.nextLine();
byte kor = Byte.parseByte(input_str);
if(!sj.check_jumsu(kor)){
sc.close();
return; // return 을 만나면 해당 메소드는 종료된다.
}
else{
sj.kor = kor;
} catch(NumberFormatException e) {
e.printStackTrace() // 에러위치 알려줌.
System.out.println(e.getMessage); // 에러 입력값 알려줌
System.out.println("입력하신 " + input_str + " 는 올바른 데이터가 아닙니다");
}
try{ ~~~
if(!sj.check_jumsu(kor)){
sc.close();
return;
} else {
sj.kor = kor;
}
} catch (NumberFormatException e) {
e.printStackTrace();
System.out.println(e.getMessage());
} // try-catch 문 종료
System.out.println("나이 : ");
try{
input_str = sc.nextLine();
short age = Short.parseShort(input_str);
if(!sj.check_age(age)) {
sc.close();
return;
}
~~~
} catch (NumberFormatException e) {
System.out.println("입력하신 " + input_str + "는 올바른 데이터가 아닙니다.\n"
+ "[ 나이에 대한 경고 ] 나이는 20살 이상만 입력해주세요");
int status = 0; // 점수를 입력해주는 상태 : 1
// 나이를 입력해주는 상태 : 2
try{
status = 1;
System.out.print("국어 점수 : ");
input_str = sc.nextLine();
byte kor = Byte.parseByte(input_str);
if(!sj.check_jumsu(kor)) {
sc.close();
return;
} else {
sj.kor = kor;
}
status = 2;
System.out.print("나이 : ");
input_str = sc.nextLine();
short age = Short.parseShort(input_str);
if(!sj.check_age(age)) {
sc.close();
return;
} else {
sj.age = age;
}
} catch (NumberFormatException e) {
System.out.println("입력하신 " + input_str + "는 올바른 데이터가 아닙니다.\n");
if(status == 1) { // 점수를 입력한 상태
System.out.println("[ 점수에 대한 경고 ] 점수는 0 ~ 100 까지의 정수만 입력하세요.");
} else { // 나이를 입력한 상태
System.out.println("[ 나이에 대한 경고 ] 나이는 20살 이상만 입력해주세요");
} // if-else 종료
} // try-catch 문 종료
sc.close();
my.day03.c.scanner -> Main_scanner_2
my.day04.b.sungjuk -> Main_Sungjuk