Binary World

JAVA CLASS : 예외(Exception) 본문

개발자의 길/JAVA

JAVA CLASS : 예외(Exception)

모쿠 2017. 1. 12. 13:45

<예외(Exception)>


* 컴파일 에러, 예외, 논리적 오류

  1. 컴파일 에러 : 소스코드 빌드시 발생하는 에러

  -> 실행 파일이 만들어지지 않기 때문에 실행할 수 없음.

  2. 예외(Exception)

  -> 소스코드를 빌드할 때는 에러가 없었지만, 실행 파일을 실행 할 때 발생하는 오류

  3. 논리적 오류:

  -> 컴파일 에러도 없고, 실행할 때 예외도 발생하지 않지만 논리적인 문제 때문에 원하는 실행결과가 나오지 않는 경우


<프로그램 코드>


1. 하나의 try 구문에서 여러개의 catch문을 사용하는 방법


* ExMain05.java


package edu.java.exception05;


public class ExMain05 {


public static void main(String[] args) {

// 하나의 try 구문에서 여러개의 catch를 사용하는 방법 1

try {

int x = 12345;

int y = 100;

int result = x / y;

System.out.println("result = " + result);


int[] array = new int[10];

array[0] = 1000;

System.out.println("array[0] = " + array[0]);

String name = null;

System.out.println("문자열 길이: " + name.length());


} catch (ArithmeticException e) {

System.out.println("산술연산 예외 : " + e.getMessage());

} catch (ArrayIndexOutOfBoundsException e){

System.out.println("인덱스 예외: " + e.getMessage());

} catch (NullPointerException e) {

System.out.println("널포인트 예외: " + e.getMessage());

}


System.out.println("프로그램 종료");

// 하나의 try구문에서 여러개의 catch를 사용할 경우,

// 자식 클래스의 Exception들을 먼저 catch 구문에서 사용하고

// 부모 클래스인 Exception을 마지막에 사용해야 함


} // end main()


} // end class ExMain05 


* 출력화면


result = 123

array[0] = 1000

널포인트 예외: null

프로그램 종료



* ExMain06,java


package edu.java.exception06;


public class ExMain06 {


public static void main(String[] args) {

// 하나의 try구문에서 여러개의 catch를 사용하는 방법2 : Java 7버전부터 가능

// try{

//    정상 상황일 때 실행할 코드;

// } catch (Ex1 | Ex2 | Ex3 ... e) {

// 예외 상황일 때 실행할 코드;

// }

// 예외(Exception)의 종류들을 나열할 때는 부모 예외 클래스가 포함되면 안됨!

// 최상위 예외 클래스(Exception)은 항상 마지막 catch 구문에서만 사용!

try {

int result = 123 / 10;


int[] array = new int[10];

array[10] = 10;


} catch (ArithmeticException | NegativeArraySizeException | ArrayIndexOutOfBoundsException e) {

System.out.println("예외: " + e.getMessage());

}

System.out.println("프로그램 종료");


}


}


* 출력화면


예외: 10

프로그램 종료 



2. finally 사용 (모든 경우에서 반드시 실행)


* ExMain07.java


package edu.java.exception07;


public class ExMain07 {


public static void main(String[] args) {

// try { 정상적인 경우에 실행할 코드들;

// } catch (Exception e) { 예외 상황일 때 실행할 코드;

// } finally {

// 모든 경우에서 반드시 실행할 코드;

// }

// (주의) try 블록이나 catch 블록 안에 return; 이 있더라도

// return 보다 먼저 finally 블록이 실행되고, 그 후에 return이 실행됨!


try {

System.out.println("try 시작");

int result = 123 / 10;

System.out.println("try 끝");

} catch (Exception e) {

System.out.println("예외: " + e.getMessage());

return; // main() 메소드 종료

} finally {

System.out.println("finally: 언제 실행될까요?");

}

System.out.println("프로그램 종료");

}




* 출력화면 


try 시작

try 끝

finally: 언제 실행될까요?

프로그램 종료



3. 사용자 정의 예외(Exception) 클래스 생성법


* ExMain09.java


package edu.java.exception09;


import java.util.Scanner;


// 사용자 정의 예외(Exception) 클래스를 만드는 방법

class ScoreInputException extends Exception {

public ScoreInputException(String msg) {

super(msg);

}

} // end class ScoreInputException


class AgeInputException extends Exception {

public AgeInputException(String msg) {

super(msg);

}

}


public class ExMain09 {


private static Scanner sc = new Scanner(System.in);


public static void main(String[] args) {

int korean = 0;

try {

korean = inputScore();

} catch (ScoreInputException e) {

// TODO Auto-generated catch block

System.out.println(e.getMessage());

}

System.out.println("국어 점수: " + korean);



try {

int age = inputAge();

System.out.println("나이 :" + age);

} catch (AgeInputException e) {

System.out.println("예외: " + e.getMessage());

}


sc.close();


} // end main()


// 2. 메소드 선언 부분에 throws Exception을 추가

private static int inputScore() throws ScoreInputException {

System.out.println("점수 입력>");

int score = sc.nextInt();

// 입력 받은 점수가 0 ~ 100사이가 아니면

// 예외(Exception)를 생성해서 던짐(throw)

if (score < 0 || score > 100) {

ScoreInputException ex = new ScoreInputException("0~100사이에 입력하세용");

throw ex;

}


return score;

} // end inputScore()


private static int inputAge() throws AgeInputException {

System.out.println("나이 입력>");

int age = sc.nextInt();

if (age < 0) {

AgeInputException ex = new AgeInputException("나이 입력 오류");

throw ex;

}



return age;


}


} // end class ExMain09


* 출력화면


점수 입력>

1111

0~100사이에 입력하세용

국어 점수: 0

나이 입력>

22

나이 :22


Comments