Day038

RISK_TAKER·2023년 3월 24일

예외 떠 넘기기

  • throws : 메소드 선언부 끝에 작성한다. 예외 처리를 호출한 곳으로 떠 넘기는 역할을 한다. main 메소드에서는 사용할 수 없고, try-catch로 예외를 처리해야 한다.

예외 발생시키기

  • 코드에서 예외 발생시킨다.
    throw new Exception("예외 메시지");

예외 정보 얻기

  1. getMessage()
  2. printStackTrace()

사용자 정의 예외 & 예외 발생

  • 클래스 선언
	class HungryException extends Exception {
		public HungryException(String msg) {
			super(msg);
		}
	}
    class NoPowerException extends Exception {
		public NoPowerException(String msg) {
			super(msg); //Exception(메시지) super(메시지) -> detailMessage = 메시지;
		}
	}
  • 예외를 발생시키는 부분
	public static int energy() throws Exception {
		int n = -2;

//		return -1; 힘이없다.
		if (n == -1) {
			throw new NoPowerException("힘이 없다");
		}

		if (n == -2) {
			throw new HungryException("배고프다");
		}
//		return -2; 배고프다.
		return 8; // 0~10 가진 에너지
	}
  • 예외를 처리하는 부분
	try {
			int energy = energy();
			System.out.println("남은에너지:" + energy);
		} catch (NoPowerException e) {
			System.out.println("NoPowerException 인식 완료");
			System.out.println(e.getMessage());
		} catch (HungryException e) {
			System.out.println("HungryException 인식 완료");
			System.out.println(e.getMessage());
		} catch (Exception e) {
//			System.out.println("문제가 발생함.");
			System.out.println(e.getMessage());
		}

java API

  • Integer 클래스
  • Object 클래스
  • 객체 해시코드

컬렉션 프레임워크

  • 컬렉션
    List : 순서를 유지하고 저장, 중복 저장 가능
    Set : 순서를 유지하지 않고 저장, 중복 저장 안됨
    Map : 키와 값의 쌍으로 저장, 키는 중복 저장 안됨

-HashMap : 동일한 키값이 들어오면 덮어쓰기가 된다.

0개의 댓글