try & catch
package ex2_try_catch;
public class Ex1_try_catch {
public static void main(String[] args) {
//예외 처리 과정
//1. 코드 진행중 예외가 발생하면 JVM에게 알린다
//2. JVM은 발생한 예외를 분석하여 알맞은 예외 클래스를 생성한다
//3. 생성된 예외 객체를 발생한 지점으로 보낸다
//4. 예외가 발생한 지점에서 처리하지 않으면 프로그램은 비정상 종료된다
//예외 처리 문법
// try{
// 예외가 발생할 수 있는 코드
// } catch(예외 클래스명 e){
// 예외 처리 코드
// }
int result = 0;
try {
result = 10 / 0;
System.out.println("계산결과 : "+result);
} catch(ArithmeticException e) {
System.out.println("0으로 나눌 수 없습니다.");
}
}
}
try & catch 예제
package ex2_try_catch;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Ex2_try_catch {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try {
System.out.printf("점수를 입력하세요 : ");
int score = sc.nextInt();
if(score>=65)
System.out.println("합격입니다.");
else
System.out.println("불합격입니다.");
} catch(InputMismatchException e) {
System.out.println("키보드 입력이 잘못되었습니다.");
}
System.out.println("프로그램 종료");
sc.close();
}
}
다중 catch
package ex2_try_catch;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Ex3_try_catch {
public static void main(String[] args) {
//다중 catch 사용
//try 구문 내에서 다양한 예외가 발생할 수 있는 경우
//catch 구문을 여러개 작성하여 예외별로 처리가 가능하다
Scanner sc = new Scanner(System.in);
try {
int cards[] = {4,5,1,2,7,8};
System.out.printf("몇번째 카드를 뽑으시겠습니까? : ");
int cardIndex = sc.nextInt();
System.out.printf("뽑은 카드 번호는 : %d입니다.", cards[cardIndex-1]);
} catch(InputMismatchException e) {
System.out.println("숫자만 입력 가능합니다.");
} catch(IndexOutOfBoundsException e) {
System.out.println("입력한 번호의 카드는 존재하지 않습니다.");
} catch(Exception e) {
System.out.println("오류 발생");
}
sc.close();
}
}
Finally
package ex2_try_catch;
import java.util.Scanner;
public class Ex4_finally {
public static void main(String[] args) {
//finally 블록은 예외 발생 여부와 상관없이 실행되는 구문
//필요없다면 생략이 가능
//예외가 발생해도 정상 종료되어야 할 구문들에서 사용
Scanner sc = new Scanner(System.in);
try {
System.out.printf("점수를 입력하세요 : ");
int score = sc.nextInt();
if(score >= 60)
System.out.println("합격입니다.");
else
System.out.println("불합격입니다.");
} catch(Exception e) {
System.out.println("키보드 입력이 올바르지 않습니다.");
} finally {
System.out.println("프로그램 종료");
}
sc.close();
}
}
throw exception
package ex3_try_catch;
import java.util.InputMismatchException;
import java.util.Scanner;
public class ThrowsExceptionTest {
public static void checkYourself(Scanner scan) throws InputMismatchException {
System.out.println("1. 나는 사람들과 어울리는 것이 좋다 2. 혼자 있는것이 좋다.");
System.out.printf("선택 : ");
int check = scan.nextInt();
if(check==1)
System.out.println("당신은 enfp");
else
System.out.println("당신은 isfp");
}
public static void main(String[] args) {
// 예외 던지기
// 우리가 호출한 메서드 내부에서 예외가 발생한 경우
// 메서드 내부에서 try-catch로 처리할 수 있다.
// 하지만 내부에서 처리하지 않고 메서드를 호출한 곳에서
// 예외를 처리하도록 하는 기법
Scanner sc = new Scanner(System.in);
try {
System.out.println("성격 유형 검사 시작");
ThrowsExceptionTest.checkYourself(sc);
} catch (Exception e) {
System.out.println("키보드 입력이 잘못되었습니다.");
} finally {
System.out.println("프로그램 종료");
}
}
}