예외처리 와 제네릭컬렉션

2023. 12. 11. 21:07Daily Codig Reminder

9장 예외처리

예외가 발생되었을 때 프로그램을 비정상 종료하지 않고 정상 종료 되게 처리하는 것

 

System.out.println("프로그램 시작");
		try {
		
		int num= 10;
		int result = num/0;
		System.out.println(result); //ArithmeticException
		}catch(ArithmeticException e) {//handling 할 ex객체명 
			System.out.println("예외 발생");
		}
		System.out.println("프로그램 종료");

 

2.1 try~catch~finally 문 이용

try{
//예외발생코드
}catch(예외클래스명 변수명){
//예외처리코드
}

 

System.out.println("프로그램 시작");
		
		try {
		int num= 10;
		int result = num/0;
		System.out.println(result); //ArithmeticException
		}catch(Exception e) {//handling 할 ex객체명 
			e.printStackTrace(); // 예외 발생원인을 찍어줌
			System.out.println("예외 발생" +e.getMessage());
		}
		System.out.println("프로그램 종료");

Exception 이 상위 변수라 다 걸림

 

2.2 다중 catch 문

 

try{
 //예외발생코드1
 //예외발생코드2
}catch(예외클래스명1 변수명){
 //예외처리코드
}catch(예외클래스명2 변수명){
 //예외처리코드
}

 

System.out.println("프로그램 시작");
		
		try {
			
			int num=10;
			int result = num /10; 
			
			String name = "abc";
			System.out.println(name.length());
			System.out.println(result);
			System.out.println(name);
			
			int[] arr = new int[3];
			arr [10]=10;
		} catch  (ArithmeticException e){
			System.out.println("ArithmeticException 예외처리함");
			System.out.println(e.getMessage());
			
		}catch (NullPointerException e) {
			System.out.println("NullPointerException 예외처리");
			System.out.println(e.getMessage());
			
		}catch (Exception e){ // 이거 하나만 써도 잘 잡힘
			System.out.println("Exception 예외처리");
			System.out.println(e.getMessage());
		}
			System.out.println("프로그램 종료");
		}

 

프로그램 시작
3
1
abc
Exception 예외처리
Index 10 out of bounds for length 3
프로그램 종료

 

System.out.println("프로그램 시작");
		try {
			//작업1
			int num=10;
			int result = num/1;
			System.out.println(result);
			
			String name="a";
			System.out.println(name.length());
			
			int [] num2 = {10,20};
			System.out.println(num2[3]);
		}catch (Exception e) {
			System.out.println("예외발생3 "+e.getMessage());
		}
		System.out.println("프로그램 종료");

 

프로그램 시작
10
1
예외발생3 Index 3 out of bounds for length 2
프로그램 종료

 

System.out.println("프로그램 시작");
		try {
			//작업1
			int num=10;
			int result = num/0;
			System.out.println(result);
		}catch(ArithmeticException e){
				System.out.println("예외발생1"+e.getMessage());
			}
			try {
				
			
			String name=null;
			System.out.println(name.length());
			
		}catch (NullPointerException e) {
			System.out.println("예외발생2 "+e.getMessage());
		}
		System.out.println("프로그램 종료");

 

프로그램 시작
예외발생1/ by zero
예외발생2 null
프로그램 종료

 

2.3 finally 문

 

try{
//예외발생코드1
}catch(예외클래스명1 변수명){
//예외처리코드
}finally{
//반드시 수행하는 문장
}

 

int num =10;
		try {

		// 작업1
        num = 10;
       int result = num / 2;
       System.out.println(result);

       // 작업2

       String name = "aa";
       System.out.println(name.length());

       // 작업3==> 우리가 알고 있는 예외가 아니다.
       int[] num2 = { 10, 20 };
       System.out.println(num2[1]);
		}catch(NullPointerException e) {
			System.out.println("예외발생1"+e.getMessage());
			
		}catch (ArithmeticException e) {
			System.out.println("예외발생2"+ e.getMessage());
		}catch(Exception e){
			System.out.println("예외발생3"+e.getMessage());
		}finally {
			System.out.println("finally 부분 실행됨 ==========");
		}System.out.println(num);
		System.out.println("프로그램 종료");

 

System.out.println("프로그램 시작");
		try {
			int num =10;
			int result =10/0;
			System.out.println(num);
		}finally {
			System.out.println("반드시 수행되는 문장");
		}System.out.println("프로그램 종료");

 

public static void a() {
		System.out.println("a함수 호출");
		b();
	}

	public static void b() {
		System.out.println("b함수 호출");
	}
	public static void main(String[] args) {
		System.out.println("main 시작");
		a();
		System.out.println("main 종료");

	}

 

 

main 시작
a함수 호출
b함수 호출
main 종료

// a 시작 b호출해서 다시 a로가서 main으로 끝

 

public static void a() throws Exception {
		System.out.println("a함수 호출");
		b();//위임받은 Ex try/ catch , 2) 호출한 곳으로 다시 위임
		System.out.println("a 함수 끝");
	}

	public static void b() throws Exception { //호출한 곳으로 처리를 위임
		//ex 발생 == try catch 안함
		System.out.println("b함수 호출");
		int result =10/0;
		System.out.println("b함수 끝");
	}
	public static void main(String[] args) throws Exception {
		System.out.println("main 시작");
		try {
		a();
		}catch (Exception e) {
//		a();//위임받은 Ex try/ catch , 2)throws 작성
		System.out.println("main catch 블럭");
		}
	}

 

public static void a() { //호출한 곳으로 위임
		try {
			b();
		}catch (Exception e) {
			System.out.println("a함수 catch 실행");
		}
		System.out.println("a 함수 끝");
	}

	public static void b() throws Exception { //호출한 곳으로 처리를 위임
	Class.forName(null);
		System.out.println("b함수 끝");
	}
	public static void main(String[] args) throws Exception {
		System.out.println("main 시작");
//		try {
		a();
//		}catch (Exception e) {
//		a();//위임받은 Ex try/ catch , 2)throws 작성
		System.out.println("main catch 블럭");
		}
	}

//}

 

main 시작
a함수 catch 실행
a 함수 끝
main catch 블럭

 

public static void a() throws Exception { //호출한 곳으로 위임
	
			b();
		System.out.println("a 함수 끝");
	}

	public static void b(){ //호출한 곳으로 처리를 위임
	try {
		Class.forName(null); //ex
	}catch(Exception e) {
		System.out.println("==================");
		e.printStackTrace();
	}System.out.println(" b 종료=============");
	}
	public static void main(String[] args) throws Exception {
		System.out.println("main 시작");
		try {
		a();
		}catch (Exception e) {
//		a();//위임받은 Ex try/ catch , 2)throws 작성
			System.out.println("main 에서 처리함 : "+ e.getMessage());
		}
		System.out.println("main 프로그램 종료");
		}
	}

 

 

public static void b() {
		System.out.println("b함수 실행됨");
	
	try {
		int result =10/0;
		
	}catch(Exception e) {
		System.out.println("Exception "+e.getMessage());
	}
	System.out.println("b함수 종료됨");
	}
	public static void a(){ //호출한 곳으로 위임
		System.out.println("a 실행됨");
		b();
	System.out.println("a 함수 끝");
}

	public static void main(String[] args) {
		System.out.println("main프로그램시작");
		a();
		System.out.println("main프로그램종료");

	}

 

public class ExceptionTest8_3 {
	public static void a() throws ArithmeticException, NullPointerException { //호출한 곳으로 위임
		System.out.println("a 실행됨");
		b();
	System.out.println("a 함수 끝");
}
public static void b() throws ArithmeticException, NullPointerException {
		System.out.println("b함수 실행됨");
	
	
//		int result =10/0;
		String name= null;
		System.out.println(name.length());
	
	System.out.println("b함수 종료됨");
	}
	
	 public static void main(String[] args) {

	        System.out.println("main 프로그램 시작");

	        try {
	            a();
	        }catch(Exception e) {
	            System.out.println(e.getMessage());
	        }

	        System.out.println("main 프로그램 종료");
	}

	}

 

public class ExceptionTest8_4 {

    private static void a() throws Exception {
        System.out.println("a함수 호출");

        b();

        System.out.println("a함수 종료");
    }


    private static void b() throws Exception{
        System.out.println("b함수 호출");

//            int result = 10/0;
            String name = null;
            System.out.println(name.length());

        System.out.println("b함수 종료");
    }


    public static void main(String[] args) {

        System.out.println("main 프로그램 시작");

        try {
            a();
        }catch(Exception e) {
            System.out.println(e.getMessage());
        }

        System.out.println("main 프로그램 종료");

    }//end main
}

 

2.4 throws 키워드를 이용한 예외처리 위임

지정자 리턴타입 메서드명( [파라미터] ) throws 예외클래스,예외클래스2 { }

 

§ 메서드 리턴타입이 반드시 동일해야 된다. 단, 상속관계인 경우에 작은 타입으로 지정이 가능하다.
§ 메서드명이 반드시 동일해야 된다.
§ 메서드 인자 리스트가 반드시 동일해야 된다.
§ 접근지정자는 같거나 큰 레벨만 가능하다.
§ throws 예외클래스는 계층구조에서 같거나 작은 타입만 가능하다.

 

3. throw 이용한 명시적 예외 발생

 

조건에 맞으면 명시적으로 예외를 발생시킨다

 

if(조건) throw new XXXException([인자]);

 

public static void a() {
		int num=10;
		try {
			if (num>0) {
				throw new ArithmeticException("num은 0보다 큼");
			}
		}catch(Exception e) {
			System.out.println("catch 부분에서 실행함: "+e.getMessage());
		}System.out.println("a함수 종료 ================");
	}

	public static void main(String[] args) {
		System.out.println("프로그램 시작");
		a();
System.out.println("프로그램 정상 종료");
	}

 

프로그램 시작
catch 부분에서 실행함: num은 0보다 큼
a함수 종료 ================
프로그램 정상 종료

 

public static void a() throws ArithmeticException {
		int num=10;
		
			if (num>0) {
				throw new ArithmeticException("num은 0보다 큼");
			}
		
	System.out.println("a함수 종료 ================");
	}

	public static void main(String[] args) {
		System.out.println("프로그램 시작");
		try {
		a();
		}catch(Exception e) {
System.out.println("프로그램 정상 종료");
	}

}}

 

 

프로그램 시작
프로그램 정상 종료

 

public class ExceptionTest111 {
public static void a() {
	b();
}
public static void b() {
	int num =10;
	int result = num/0;
	System.out.println(result);
}
	public static void main(String[] args) {
		System.out.println("프로그램 시작");
		try {
			a();
		}catch(ArithmeticException e) {
			System.out.println(e.getMessage()+": catch문 실행");
		}
System.out.println("프로그램 종료");
	}

}

 

프로그램 시작
/ by zero: catch문 실행
프로그램 종료

 

4. 사용자 정의 예외클래스

public class ExceptionTest12_0 {
public static void a() throws UserException{
	b();
}
public static void b() throws UserException{
	if (true) throw new UserException("사용자 정의 ex강제 발생");
	System.out.println("b함수 종료");
}

	public static void main(String[] args) {
		System.out.println("프로그램 시작");
		try {
			a();
		}catch(UserException e) {
			System.out.println(e.getMessage());
		}
		System.out.println("프로그램 종료");

	}

}

 

프로그램 시작
사용자 정의 ex강제 발생
프로그램 종료

 

public class ExceptionTest12_1 {
public static void a(){
	b();
}
public static void b(){
	try {
		
	
	if (true) throw new UserException("사용자 정의 ex강제 발생");
	}catch(Exception e) {
	System.out.println(e.getMessage());
}
	System.out.println("b함수 종료");
}
	public static void main(String[] args) {
		System.out.println("프로그램 시작");
		
			a();


		System.out.println("프로그램 종료");

	}

}

 

프로그램 시작
사용자 정의 ex강제 발생
b함수 종료
프로그램 종료

 

public class UserException2 extends Exception{

	public UserException2(String mesg) {
		super(mesg);
		// TODO Auto-generated constructor stub
	}
}

 

 

import java.util.Random;

public class ExceptionTest13 {
	public static void myRandom() {
		Random r = new Random();
		int num = r.nextInt(3);
		System.out.println(num);
		if (num==0) {
			try {
				throw new UserException2("랜덤값 0이 나와 예외발생");
			}catch(Exception e) {
				System.out.println(e.getMessage());
			}
		}
	}

	public static void main(String[] args) {
		System.out.println("프로그램 시작");
		myRandom();
		System.out.println("프로그램 종료");

	}

}

 

 

class ByZeroException extends Exception{
		public ByZeroException (String mesg) {
			super(mesg);
		}
	}
	public class Ex09_9 {
		public static void divide() throws ByZeroException{
			try {
				int num = 3/0;
			}catch (ArithmeticException e) {
				throw new ByZeroException("0으로 나누어 예외발생~");
			}
		}
	public static void main(String[] args) {
		System.out.println("프로그램 시작");
		try {
			divide();
		}catch(ByZeroException e){
			System.out.println("에외 발생: "+e.getMessage());
		}
		System.out.println("프로그램 정상 종료");

	}

}

 

 

프로그램 시작
에외 발생: 0으로 나누어 예외발생
프로그램 정상 종료

 

10장. 제네릭과 컬렉션 API

 

1. 제네릭

package com;

import java.util.Date;

//Object 대신에 T(Type)의미로서 참조형 타입만 지정 가능

class Box1<T>{
    T obj;

    public void setValue(T obj) {
        this.obj = obj;
    }

    public T getValue() {
        return obj;
    }
}//end Box

public class GenericTest1 {

    public static void main(String[] args) {
        //제너릭스 타입(generics type)
        //1. 앞와 뒤 둘 다 선언
        Box1<String> b = new Box1<String>();

        b.setValue("hello");
//        b.setValue(100);//에러 : generic 선언 때문에
        String x = b.getValue();//형변환 필요없음
//        Date xx = (Date)b.getValue();
        System.out.println(x.length());

        //2. 앞에만 선언
        Box1<Date> b2 = new Box1<>();
        b2.setValue(new Date());
//        b2.setValue("aaa");//에러
        Date d = b2.getValue();//형변환 필요없음
        System.out.println(d);

        Box1<Integer> b3 = new Box1<>();
        b3.setValue(100);
//        b3.setValue("100"); error
        int xxx = b3.getValue();//오토언박싱
        //오토언박싱이 안되는 경우
        Integer xxx2 = b3.getValue();
        int xxx3 = xxx2.intValue();
        System.out.println(xxx);
        //3.
        Box1 b4 = new Box1(); //Generic 사용 안하는 경우 Object 가 기본
        b4.setValue("aaaa");
        b4.setValue(100);
        b4.setValue("hello");
        String ssss = (String)b4.getValue();
System.out.println(ssss.length()); //형변환 필요

    }}

 

 

public class Test2 {

	public static void main(String[] args) {
		Object []arr = {"홍길동","이순신","유관순",100};
	for (Object obj : arr) {
		if (obj instanceof String) {
		String name =(String)obj;
		System.out.println("이름: "+name);
	}

	}

	}} //

 

instanceof 연산자를 사용하여 String타입과 일 치하는 경우에만 형변환 하도록 처리한다

 

2. 컬렉션

 

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

public class SetTest {

	public static void main(String[] args) {
		//다형성 ,generic 사용안함
		Set set = new HashSet();
		set.add("1");
		set.add("2");
		set.add(3);
		set.add("4");
		set.add(3.14);
		set.add(new Date());
		
		System.out.println("길이: "+set.size());
		System.out.println("포함여부: "+set.contains(20));
		System.out.println("empty:"+set.isEmpty());
		System.out.println(set);
		
		Object [] xxx = set.toArray();
		for (Object o : xxx) {
			System.out.println(o);
		}set.clear();
		System.out.println(set);

	}

}

 

 

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class SetTest3_1 {

	public static void main(String[] args) {
		
		Set <Person> set = new HashSet<>();
		
		Person kkkk = new Person("유관순",17,"서울");
		set.add( new Person("이순신",44,"전라"));
		set.add( new Person("이순신",44,"전라"));
		set.add( new Person("홍길동",20,"서울"));
		set.add(kkkk);
		set.add(kkkk);
//		set.add("aaa");
		System.out.println(set);
		
		for (Person x : set) {
			System.out.println(x.getName());
		}System.out.println("============= itrator 사용 순회");
		Iterator<Person> ite = set.iterator();
		 while(ite.hasNext()) {
	            Person p = ite.next();
	            System.out.println(p.getName());
	        }

	}

}

 

 

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class SetTest3_2 {

	public static void main(String[] args) {
		
		Set  set = new HashSet();
		
		Person kkkk = new Person("유관순",17,"서울");
		set.add( new Person("이순신",44,"전라"));
		set.add( new Person("이순신",44,"전라"));
		set.add( new Person("홍길동",20,"서울"));
		set.add(kkkk);
		set.add(kkkk);
//		set.add("hello");
//		set.add("aaa");
		System.out.println(set);
		Object[]arr = set.toArray();
		for (int i = 0; i < arr.length; i++) {
			Object object = arr[i];
			Person p = (Person)object;
			System.out.println(p.getName());
		}System.out.println("=============");
		for (Object o : set) {
			Person p = (Person)o;
			System.out.println(p.getName());
		}System.out.println("========== iterator 이용한 이름만 출력");
		Iterator<Person> ite = set.iterator();
		 while(ite.hasNext()) {
	            Person p = ite.next();
	            System.out.println(p.getName());
	        }
		 Iterator ite2 = set.iterator();
		 while(ite.hasNext()) {
			 Person p = (Person)ite2.next();
	            System.out.println(p.getName());
	        }
	}}

 

 

import java.util.HashSet;
import java.util.Set;

public class SetTest4 {

	public static void change (int num) {
		num =100;
	}
	public static void change2 (int[] num) {
		num[0] =0;
	}
	public static void change3 (HashSet<String>set) {
		set.remove("홍길동");
	}
	public static void change4 (Set <String>set) {
		set.remove("홍길동");
	}
	public  Set<String> getSet(){
		Set<String> set = new HashSet<>();
		set.add("1");
		set.add("2");
		return set;
		
	}
	
	//main 에서 getset 함수호출 리턴받은 set데이터 순회 출력
	
	
	public static void main(String[] args) {
		
		int m =10;
		System.out.println("변경 전: "+ m);
		change(m);
		System.out.println("변경 후: "+m);
		////////////////////////
		int []m2 = {9,8,7};
		System.out.println("변경 전: "+ m2[0]);
		change2(m2);
		System.out.println("변경 후: "+m2[0]);
		/////////////////////
		System.out.println("변경 전: "+ m2[0]);
		change(m2[0]);
		System.out.println("변경 후: "+m2[0]);
		//////////////////////////////
		HashSet<String>set = new HashSet<String>();
		set.add("홍길동");
		set.add("이순신");
		set.add("유관순");
	System.out.println("변경 전: "+set);
//	change3(set);
	change4(set);
	System.out.println("변경 후: "+set);
	///////////////////////
	SetTest4 test4 = new SetTest4();
    Set<String> set2 = test4.getSet();

    for (String s : set2) {

        System.out.println(s);

    }
	}
}

 

 

package com.dao;

import java.util.HashSet;

public class OracleDAO {
public HashSet<String>select(){
	HashSet<String> set = new HashSet<String>();
	set.add("홍길동");
	set.add("이순신");
	set.add("유관순");
	return set;
}
}

 

 

package com.dao;

import java.util.HashSet;
import java.util.Iterator;

public class OracleService {

public OracleService () {
//	dao = new OracleDAO();
	
}
public HashSet<String> select(){
	OracleDAO dao = new OracleDAO(); //호출시 생성삭제
	HashSet<String> xxx = dao.select();

	return xxx;//메인으로 출력
	
	
}

}

 

 

package com.dao;

import java.util.HashSet;

public class OracleMain {
	public static void main(String[] args) {
		
		OracleService os = new OracleService();
	    HashSet<String> xxx = os.select();
	    HashSet<String> xxx2 = os.select();
	    

	    for (String s : xxx) {
	        System.out.println(s);
	    }
	}

}

 

 

import java.awt.List;
import java.util.ArrayList;
import java.util.Date;

public class ListTest {

	public static void main(String[] args) {
		ArrayList list = new ArrayList();
		list.add("홍길동");
		list.add("이순신");
		list.add(20);
		list.add("홍길동");
		list.add(3.15);
		list.add(new Date());
		System.out.println(list.size());
		System.out.println(list);

	}

}

 

 

import java.awt.List;
import java.util.ArrayList;
import java.util.Date;

public class ListTest2 {

	public static void main(String[] args) {
		ArrayList <String> list = new ArrayList();
		list.add("홍길동");
		list.add("이순신");
		list.add("유관순");
		list.add("강감찬");
		list.add("세종");
//		list.add(100);

		System.out.println(list);
		System.out.println(list.get(0));
		System.out.println(list.get(1));
		System.out.println(list.get(2));
		System.out.println(list.get(3));
		System.out.println(list.get(4));
//System.out.println(list.get(5)); //error
		for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }
	}

}

'Daily Codig Reminder' 카테고리의 다른 글

자바 IO  (0) 2023.12.14
리스트, 맵  (0) 2023.12.12
핵심클래스  (0) 2023.12.09
다형성  (1) 2023.12.07
static, 클래스들의 관계  (1) 2023.12.06