본문 바로가기
CLASS/JAVA

#11-2 / 배열을 이용한 예외처리

by eungSe__ 2024. 5. 16.
⚡ 배열을 이용한 예외처리

package oop2;

import java.util.ArrayList;
import java.util.Arrays;

//배열을 이용한 예외처리
public class ex10 {
	public static void main(String[] args) {
		//object형태의 자료형 전체를 확인
		//System.out.println(data[4].getClass().getName()); 
		
		//간단한 자료형 이름만 출력
		//System.out.println(data[4].getClass().getSimpleName()); 
		
		Object data[] = {"유재석",1000,"실버회원",0.5,true};
		ArrayList<Integer> user = new ArrayList<Integer>(); //빈배열
		try {
			int w =0;
			while(w<data.length) {
				//Object원시배열 -> 숫자클래스 배열로 입력할 경우 자료형 변환 후 add
				String ck = data[w].getClass().getSimpleName();
				if(ck.equals("Integer")) {
					user.add(Integer.valueOf((int)data[w]));
				}
				w++;
			}
			System.out.println(user);	
		}catch(Exception e) {
			System.out.println(e);
		}
		
	}
}

 

⚡ 예외처리,배열,setter,getter(반복문 안에 try~catch)
반복문 안에 예외처리시 catch에서 반복문 종료됨! (like break)

package oop2;
import java.util.LinkedList;

public class ex11 {

	public static void main(String[] args) {
		ex11_box ex = new ex11_box();
		Object data[] = {"2000","500",1500,"15",15.25,"6000"}; //검토 안한상태
		//Object data[] = {"2000","500","1500","15","15","6000"}; 검토 한상태
		try {
			ex.setter(data);
			//원시배열을 setter로 던짐(원래는 Object배열 내부 각 자료형 검토 후 보내야함)
			
			LinkedList<Integer> result = ex.getter();
			System.out.println(result); //Object배열 내부 각 자료형 검토 후 받으면 출력됨
			//but 지금은 걍 문자,숫자 혼합형태라 
			  //문자->숫자 변환이 안되기때문에 하단 catch 영역 출력
		}catch(Exception e) {
			System.out.println(e);
		}
	}
}

//setter,getter를 이용한 DTO
class ex11_box {
	LinkedList<Integer> redata = new LinkedList<Integer>();
	
	public void setter(Object[] call) throws Exception{ //data 입력
		int ea = call.length; //받은 배열 call의 갯수
		int w=0;
		while(w<ea) {
			try {
				//두개 잘 구분, object 사용시엔 parseInt,valueOf 두개가 다름!!
				//Integer no = Integer.parseInt((String)call[w]); //여기서 (int)는 error
				Integer no = Integer.valueOf((String)call[w]); //(string),(int)둘다 먹힘
				
				this.redata.add(no); //원시배열 값을 클래스배열로 데이터 삽입
			}catch(Exception e) { //예외처리 - 오류 발생시 throw가 발생되면 반복문 강제정지!
				Exception ex = new Exception("배열에 올바른 값이 아닙니다.");
				throw ex; //반복문 종료(break처럼 아예 걍 끝나버림)
			}
			w++;
		}
	}
	
	public LinkedList<Integer> getter(){ //data 출력
		return this.redata;
	}
}

 

'CLASS > JAVA' 카테고리의 다른 글

#13-1 / String, StringBuilder, StringBuffer  (0) 2024.05.20
#12 / remind2  (0) 2024.05.17
#11-1 / Exception : 예외처리  (0) 2024.05.16
#10-2 / 단어 검토 및 변경(정규식 코드)  (0) 2024.05.14
#10-1 / Interface  (0) 2024.05.14