[개발] - Java/후발대

후발대 19일차 설명 추가

완벽한 장면 2023. 2. 24. 19:20

_03_Throw

package prac18;


//의도적 에러 만들어서 던지기
public class _03_Throw {
  public static void main(String[] args) {
    int age = 17; // 만 17세
    try {
      if(age < 19) {
        // System.out.println("만 19세 미만에게는 판매하지 않아요.");
        // 일부러 애러 발생시키기 : throw
        throw new Exception("만 19세 미만에게는 판매하지 않아요.");
      } else {
        System.out.println("주문하신 상품 여기 있습니다. ");
      }
    } catch (Exception e){
        e.printStackTrace();
    }

  }

}

 

_04_Finally

package prac18;

// catch문에서 처리한다고 해서 완전히 끝이 난 게 아닐 수도 있다.
public class _04_Finally {
  public static void main(String[] args) {
    try {
      System.out.println("택시의 문을 연다");
      // throw new Exception("휴무택시"); 예외삭제 => 문제 발생하지 않는 코드
      // System.out.println("택시에 탑승한다.");
    } catch (Exception e) {
      System.out.println("!! 문제 발생: " + e.getMessage());
    } finally {
      System.out.println("택시 문을 닫는다.");
    }
    // 어쨌건, finally는 마지막으로 실행된다!!!
    // try 구문에서 하던 것을 정리하는 구문을 넣어주면 된다.

    // try + catch(s)
    // try + catch(s) + finally
    // try + finally
    // try단독 x

    System.out.println("----------");

    //예시
    try {
      System.out.println(3/0);
    } finally {
      System.out.println("프로그램 정상 종료");
    }

  }
}

 

_05_TryWithResources

package prac18;

import java.io.BufferedWriter;

public class _05_TryWithResources {
  public static void main(String[] args) {
    MyFileWriter writer1 = null;

    try {
      writer1 = new MyFileWriter(); // 객체 생성
      writer1.write("아이스크림 사주세요.");
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
     try {
       writer1.close(); // 처음엔 빨간줄 surround with catch 써서 try-catch문 한번 더 써준다.
     } catch (Exception e) {
       throw new RuntimeException(e);
     }
    }

    System.out.println("_______");

    try(MyFileWriter writer2 = new MyFileWriter()) {
      writer2.write("빵이 먹고 싶어요");
    } catch (Exception e) {
      e.printStackTrace();
    }
      /*
  try with resources
  try 내에서 사용할 파일 객체 등을 괄호 속에 정의해주게 되면, try-catch 문을 빠져 나올 때,
  자동으로 닫는 메서드(close)를 실행해준다.
  그런데 여기서 조건이 있는데, AutoCloseable 이라는 인터페이스를 구현해줘야 한다.
   */
  }
}

class MyFileWriter implements AutoCloseable {

  @Override
  public void close() throws Exception {
    System.out.println("파일을 정상적으로 닫습니다.");
  }

  BufferedWriter bw = null;


  public void write(String line) {
    System.out.println("파일의 내용을 입력합니다.");
    System.out.println("입력 내용: " + line);
  }
  // 지금 MyfileWriter을 이용하게 되면, write 메서드 통해 파일 내용을 쓸 수가 있고,
  // close 메서드 통해 파일을 다 쓴 후에 닫을 수 있도록 코드를 작성해뒀음.

}
728x90
반응형