예외처리 과정
1. 코드 진행중 예외가 발생하면 JVM에게 알린다.
2. JVM은 발생한 예외를 분석하여 알맞은 예외 클래스를 생성한다.
3. 생성된 예외 객체를 발생한 지점으로 보낸다.
예외가 발생한 지점에서 처리하지 않으묜 프로그램은 비정상 종료된다.
try - catch
- 예외를 처리하는 가장 기본 문법
try {
//예외가 발생할 가능성이 있는 코드
} catch(예외클래스명 e) {
//예외 처리 코드
}
코드진행 -> 오류! -> JVM예외 객체 발생 -> catch 확인
실습 1)
NonTryCatchExam
public class NonTryCatchExam{
public static void main(String[] args) {
int num = 15;
int result = num / 0;
System.out.println("결과 : " + result);
Sytem.out.println("프로그램 종료");
}
}
-> Exception in thread "main" java.lang.ArithmeticException : / by zero
실습 2)
TryCatchExam
public class TryCatchExam{
public static void main(String[] args) {
try {
int num = 15;
int result = num / 0;
System.out.println("결과 : " + result);
}catch(ArithmeticExcetion e) {
System.out.println("0으로 나눌 수 없습니다.");
e.printStackTrace(); //내부에서 에러난 내용 전체 출력
System.out.println(e.getMessage());//에러 메시지만 출력
}
Sytem.out.println("프로그램 종료");
}
}
-> 0으로 나눌 수 없습니다.
java.lang.ArithmeticExcetion : / by zero
/ by zero
프로그램 종료
실습 3)
다중 catch
public class TryCatchExam{
public static void main(String[] args) {
try {
int num = 15;
int result = num / 10;
System.out.println("결과 : " + result);
}catch(ArithmeticExcetion e) {
System.out.println("0으로 나눌 수 없습니다.");
e.printStackTrace(); //내부에서 에러난 내용 전체 출력
System.out.println(e.getMessage());//에러 메시지만 출력
}catch(NullPointerExeption e) {
System.out.println("사용하려는 객체가 존재하지 않습니다.");
}
Sytem.out.println("프로그램 종료");
}
}
-> 결과 : 1
사용하려는 객체가 존재하지 않습니다.
프로그램 종료
실습 4)
MultiCatchExam
import java.util.InputMismatchException;
import java.util.Scanner;
public class MultiCatchExam {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
try {
int[] cards = {4, 2, 5, 6, 7, 1, 3};
System.out.println("몇번째 카드를 뽑으실건가요!");
int cardIndex = scan.nextInt();
System.out.println("뽑은 카드번호는 :" + cards[cardIndex]);
}catch (InputMismatchException e) {
System.out.println("키입력이 잘못되었습니다.");
}catch (ArrayIndexOutOfBoundsException e) {
System.out.println("선택된 배열 위치가 잘못되었습니다.");
}
-> 몇번째 카드를 뽑으실건가요!
[직접입력 ex] 10
선택된 배열 위치가 잘못되었습니다.
예외처리는 발생한 예외를 잘 다독여서 강제 종료가 되는것을 막고, 왜 발생한건지
, 어디서 발생한건지, 어디서 발생한건지를 개발자에게 신속히 알려서
어디서 문제가 있는지 신속히찾아 우리의 프로그램을 원활하게 만들어줌.
finally
-finally 블록은 예외발생 유무와 상관없이 실행되는 구문이며 생략 할 수 있다.
import java.util.InputMismatchException;
import java.util.Scanner;
public class MultiCatchExam {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
try {
int[] cards = {4, 2, 5, 6, 7, 1, 3};
System.out.println("몇번째 카드를 뽑으실건가요!");
int cardIndex = scan.nextInt();
System.out.println("뽑은 카드번호는 :" + cards[cardIndex]);
}catch (InputMismatchException e) {
System.out.println("키입력이 잘못되었습니다.");
}catch (ArrayIndexOutOfBoundsException e) {
System.out.println("선택된 배열 위치가 잘못되었습니다.");
}finally {
//예외가 발생유무와 상관없이 무조건 실행
System.out.println("예외끝")
scan.close"();
}
}
-> 몇번째 카드를 뽑으실건가요!
[직접입력 ex] 3
뽑은 카드번호는 : 6
예외끝
예외 던지기
import java.util.InputMismatchException;
import java.util.Scanner;
public class ThrowableExam {
public static void checkYourSelf(Scanner scan) throws InputMismatchException {
System.out.pintln("1. 사람과 어울리는 것이 좋다. / 2. 혼자 있는 것이 좋다. ");
System.out,println("선택 >> ");
int check = scan.nextInt();
if(check == 1){
System.out.println("당신은 외향적");
System.out.println("당신은 내향적");
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
try {
System.out.println("==== 성격 유형 검사를 시작합니다 ====");
ThrowableExam.checkYourSelf(scan);
}catch (InputMismatchException e) {
System.out.println("키보드 입력이 잘못되었습니다.");
}finally {
if(scan != null) {
scan.close();
}
}
}
}
System Programming상 오류가 없다해도 프로그램의 진행상 문제 생길 경우 발생 시키는 예외