try + catch(s)
try + catch(s) + finally
try + finally
// try + catch + finally
try {
System.out.println("택시의 문을 연다.");
throw new Exception("휴무 택시");
} catch (Exception e) {
System.out.println("문제 발생 : ");
e.printStackTrace();
} finally {
System.out.println("택시의 문을 닫는다.");
}
// try + finally
try {
System.out.println(3 / 0);
} finally {
System.out.println("프로그램 정상 종료");
}
리소스 생성/반납
try 구문 안에서 사용할 리소스, 객체 등을
try() 괄호 속에서 정의하게 되면
자동으로 try catch 구문을 빠져나올 때 close를 호출한다.
단, 인터페이스 AutoCloseable을 구현해주어야한다.
// Main
try (MyfFileWriter writer2 = new MyfFileWriter()) {
writer2.write("빵이 먹고 싶어요");
} catch (Exception e) {
e.printStackTrace();
}
class MyfFileWriter implements AutoCloseable {
@Override
public void close() throws Exception {
System.out.println("파일을 정상적으로 닫습니다.");
}
public void write(String line) {
System.out.println("파일에 내용을 입력합니다.");
System.out.println("입력 내용 : " + line);
}
}
// 클래스 생성
class AgeLessThan19Exception extends Exception { // Exception 상속
// 생성자
public AgeLessThan19Exception(String message) {
super(message);
}
}
// 사용
int age = 17; // 만 17세
try {
if (age < 19) {
throw new AgeLessThan19Exception("만 19세 미만에게는 판매하지 않습니다."); // 던지기
} else {
System.out.println("주문하신 상품 여기 있습니다.");
}
} catch (AgeLessThan19Exception e) { // 던진거 받기
System.out.println("조금 더 성장한 뒤에 오세요.");
} catch (Exception e) { // 여기서 안받고 위에서 받음
System.out.println("모든 예외를 처리합니다.");
}
// Main
writeFile();
// 메소드 내에서 처리
public static void writeFile() {
try {
FileWriter writer = new FileWriter("test.txt");
throw new IOException("파일 쓰기에 실패했어요!!");
} catch (IOException e) {
e.printStackTrace();
System.out.println("writerFile 메소드 내에서 자체 해결했어요.");
}
}
//Main
try {
writeFile();
} catch (IOException e) {
e.printStackTrace();
System.out.println("메인 메소드에서 해결할게요.");
}
// Main에 던져서 처리하기
public static void writeFile() throws IOException { // 상속받기
FileWriter writer = new FileWriter("test.txt");
throw new IOException("파일 쓰기에 실패했어요!!");
}
public class _Quiz_11 {
// 인기가 많은 상품이 선착순으로 판매되는 온라인 쇼핑몰에서
// 발생할 수 있는 문제를 처리하는 프로그램을 작성하시오.
//조건
// 상품 구매 가능 시간, 상품 매진 2가지
// 각 문제에 대한 사용자 정의 예외 클래스 작성
// 에러 코드에 따른 의도적 예외 발생 및 예외 처리
// 모든 클래스는 하나의 파일에 정의
public static void main(String[] args) {
int errorCode = 2;
try {
if (errorCode == 0) {
System.out.println("상품 구매를 완료하였습니다.");
} else if (errorCode == 1) {
throw new NotOnSaleException("상품 구매 가능 시간이 아닙니다.");
} else if (errorCode == 2) {
throw new SoldOutException("해당 상품은 매진되었습니다.");
}
} catch (NotOnSaleException e) {
System.out.println(e.getMessage()); // 객체 생성시 받은 출력
System.out.println("상품 구매는 20시부터 가능합니다.");
} catch (SoldOutException e) {
System.out.println(e.getMessage());
System.out.println("다음 기회에 이용해주세요.");
}
}
}
// 에러 코드에 따른 메세지
// 에러코드 0 : 에러 없음, (상품 구매를 완료하였습니다)
// 에러코드 1 : 판매 시간 아님, 상품 구매 가능 시간이 아닙니다./ 상품 구매는 20시부터 가능합니다.
// 에러코드 2 : 매진, 해당 상품은 매진되었습니다. / 다음 기회에 이용해주세요
class NotOnSaleException extends Exception {
public NotOnSaleException(String message) {
super(message);
}
}
class SoldOutException extends Exception {
public SoldOutException(String message) {
super(message);
}
}
출처 : 프로그래머스
import java.util.*;
class Solution {
public int[] solution(int[] array, int[][] commands) {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < commands.length; i++) {
Arrays.stream(array, commands[i][0] - 1, commands[i][1]).sorted().skip(commands[i][2] - 1).limit(1).forEach(x -> list.add(x));
}
return list.stream().mapToInt(Integer::intValue).toArray();
}
}
오늘도 스트림 연습을 알고리즘으로 했다.
1. 범위를 지정해 스트림 생성
2. 오름차순 정렬
3. 몇 번째 까지 이동해서 1개 자르기
4. 자른 값 List에 추가
5. List > int[]로 변환해서 리턴