삼성SDS_멀티캠퍼스/Java

14일 차 예외처리 실습예제

박성우기 2015. 9. 25. 09:06
반응형

1. 0으로 나누었을때에 대한 예외처리 만들기

class DivideByZeroException extends ArithmeticException {
 public DivideByZeroException(){
  super("0으로 나눌수 없음.");
 }
}

public class Test {
 public static void main(String[] agrs) {
  double result;
  try{
   result = quotient(1, 0);
  }
  catch (DivideByZeroException e){
   System.out.println(e.toString());
  }
 }
 public static double quotient (int n, int d) throws DivideByZeroException{
  if (d == 0)
   throw new DivideByZeroException();
  return (double)n/d;
 }

2. 제품 코드를 입력받아 같은 형태의 입력인지 확인하여 다른 경우 예외처리.

 


import java.util.regex.Matcher;
import java.util.regex.Pattern;

class IncorrectCodeException extends Exception{
 public IncorrectCodeException(){
  super("유효하지 않은 제품코드입니다.");
 }
}
public class TestEx {
 public static void main(String[] args){
  Scanner scan = new Scanner(System.in);
  System.out.println("제품 코드를 입력하세요 ex) MD0324");
  String s = scan.nextLine();
  try{
   checkCode(s);
   System.out.println("올바른 제품코드입니다.");
  }catch(IncorrectCodeException e){
   System.out.println(e.toString());   
  }
  
  
 }
 public static void checkCode (String code) throws IncorrectCodeException{
  
  Pattern pattern = Pattern.compile("[A-Z][A-Z][0-9][0-9][0-9][0-9]");

  Matcher matcher = pattern.matcher(code);

  if(!matcher.matches())
   throw new IncorrectCodeException();

/*

//교재 518페이지.
  boolean result = Pattern.matches("[A-Z][A-Z][0-9][0-9][0-9][0-9]", code);
  if(!result)
   throw new IncorrectCodeException();  

*/
 }
 

 

 public static void checkCode  메소드를 아래와 같이 변경할수 있다.

 public static void checkCode (String code) throws IncorrectCodeException{
  if (code.length()!=6)
   throw new IncorrectCodeException();
  for (int i=0; i<6;i++){
   if(i<2){
    if(code.charAt(i)<'A'||code.charAt(i)>'Z')
     throw new IncorrectCodeException();
   }
   else{
    if(code.charAt(i)<'0'||code.charAt(i)>'9')
     throw new IncorrectCodeException();
   }
  }
 }

 

3. 배열에 저장된 숫자중에 사용자가 입력한 숫자와 비교하여 같은 숫자가 없으면 예외처리.

 

 import java.util.Scanner;

class NotFoundException extends Exception {
 public NotFoundException() {
  super("숫자를 찾을수가 없습니다.");
 }
}

public class Test2 {
 public static void main(String[] args) {
  int[] arr = { 0, 1, 2, 3, 4, 5 };
  Scanner scan = new Scanner(System.in);

  System.out.println("찾을 숫자 입력");
  int find = scan.nextInt();
  try {
   searchArray(find, arr);
   System.out.println("숫자 찾음");
  } catch (NotFoundException e) {
   System.out.println(e.toString());
  }

 }

 public static void searchArray(int find, int[] arr) throws NotFoundException {
  for (int i : arr) {
   if( i == find )
    return;
  }
  throw new NotFoundException();
 }
}

4. 은행 예금을 나타내는 잔액(balance)를 필드로 갖는 클래스를 작성후, 입출, 출금 기능을 넣어 인출 금액이 잔액보다 많으면 예외처리.

 

 

class NegativeBalanceException extends RuntimeException {
 public NegativeBalanceException() {
  super("인출금이 잔액보다 많습니다.");
 }
}

class BankAccount {
 private int balance;

 public BankAccount(int money) {
  balance = money;
 }

 public int getBalance() {
  return balance;
 }

 public void setBalance(int balance) {
  this.balance = balance;
 }

 public void deposit(int money) {
  balance += money;
 }

 public void withdraw(int money) throws NegativeBalanceException {
  if (money > balance)
   throw new NegativeBalanceException();
  else
   balance -= money;
 }
}

public class Test3 {
 public static void main(String[] args) {
  BankAccount bank = new BankAccount(30000);
  int input = 0;
  Scanner scan = new Scanner(System.in);
  while (true) {
   System.out.println("1. 예금, 2. 출금, 5. 종료");
   input = scan.nextInt();
   if (input == 5)
    break;
   else if (input == 1) {
    System.out.println("현재잔액 : "+bank.getBalance());
    System.out.println("입금할 금액 : ");
    int money = scan.nextInt();
    bank.deposit(money);
   } else if (input == 2) {
    System.out.println("현재잔액 : "+bank.getBalance());
    System.out.println("출금할 금액 : ");
    int money = scan.nextInt();
    try {
     bank.withdraw(money);

    } catch (NegativeBalanceException e) {
     // TODO: handle exception
     System.out.println(e.toString());
    }
   }
  }
 }

 



출처 : http://justbaik.tistory.com/30

반응형