⚡ 배열을 이용한 예외처리
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;
}
}