본문 바로가기
혼자서 개발새발

JAVA) 사용자 정의 예외 만들기

by 휴일이 2022. 10. 14.

 

 

사용자 정의 예외를 만들어서

학교 정보 리스트(ArrayList)에 추가하는

코딩을 해보았다

 

 

 

사용자 정의 예외(한 개만, 내용 어차피 같음)

 

package exception;

public class PersonNotFoundException extends Exception {

    public PersonNotFoundException(String msg) {
        super(msg);
    }

}

 

Person(조상) 클래스

Student, Employee, Teacher 클래스는 모두 Person 클래스를 상속받았다

 

package vo;

public class Person {

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getTel() {
        return tel;
    }

    public void setTel(String tel) {
        this.tel = tel;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", tel='" + tel + '\'' +
                ", address='" + address + '\'' +
                '}';
    }

    private String name;
    private String tel;
    private String address;

    Person(String name,String tel,String address) {
        this.name = name;
        this.tel = tel;
        this.address = address;
    }



}

 

Service 클래스 

 

 

package service;

import exception.*;
import vo.Person;

import java.util.ArrayList;
import java.util.List;

public class SchoolService {

    List<Person> list = new ArrayList<Person>();

    public int findIndex(String name) { //리스트에 이름이 있나 없나?
        int index = -1;

        for(int i=0;i<list.size();i++) {
            Person per = list.get(i); //리스트 객체를 하나씩 per에 넣어 비교
            if(per.getName().equals(name)) { //리스트에 있던(per)객체의 이름과 새 이름이 같다면
                index = i; //list 몇번에 있는지를 index에 넣는다
                break;
            }
        }
        return index; //이름이 같은 객체가 없다면 -1 반환
    }


    public void add(Person p) throws DuplicateTelException { //사람 추가
        int i = findIndex(p.getName()); //중복 이름이 있는지 확인, 없다면 -1반환
        if(i!=-1) { //-1을 반환하면
            throw new DuplicateTelException("동일 이름 사람이 있음"); //예외 발생
        } else { //-1이 아니라면 객체 추가
            list.add(p);
            System.out.println(p.getName()+"님 환영합니다");
        }


    }
    public void update(String name, Person p) throws PersonNotFoundException { //수정
        int i=findIndex(name); //중복 이름 확인, 없다면 -1반환
        if(i!=-1) { //중복 이름이 있다면
            list.add(i, p); //i(리스트 객체 번호)에 새로 받은 객체를 넣는다(수정)
            System.out.println(p.getName()+"님 수정되었습니다");
            System.out.println(list.get(i)); //어떤 정보로 수정 되었는지 출력
        } else { //중복 이름이 없다면(-1이라면)
            throw new PersonNotFoundException("없는 이름입니다"); //예외 발생
        }


    }
    public void delete(String name) throws PersonNotFoundException { //삭제
        int i=findIndex(name); //중복 이름 확인, 없다면 -1, 있다면 객체 번호 반환
        if(i!=-1) { //중복 이름이 있다면(리스트에 해당 객체가 있다면)
            list.remove(i); //리스트에 있는 해당 객체 번호 받아서 삭제
            System.out.println("삭제 완료");
        } else { //중복 이름 없다면 예외 발생
            throw new PersonNotFoundException("없는 이름입니다");
        }
    }
    public void find(String name) throws PersonNotFoundException { //검색
        int i = findIndex(name); //중복 이름 확인, 있다면 객체 번호 반환

        if(i!=-1) { //객체 번호 받았다면, (-1이 아니라면)
            System.out.println(list.get(i)); //해당 객체 내용 반환
        } else { //객체 없다면 예외 발생
            throw new PersonNotFoundException("찾는 사람이 없습니다");
        }
    }


    public void print() { //전체 출력
        for (Person p : list) { //list에 있는 객체 하나씩 p에 넣음
            System.out.println(p);
        }
    }

}

 

 

Test클래스

 

 

package service;

import exception.*;
import vo.*;

public class TestSchoolService {
    public static void main(String[] args) throws DuplicateTelException, PersonNotFoundException {

        SchoolService s = new SchoolService();

        try {
            s.add(new Student("010","휴일","부천","코딩"));
            s.add(new Employee("011","채윤","목동","10"));
            s.add(new Teacher("012","다정","소사","국어"));
        } catch(DuplicateTelException e) {
            System.out.println(e.getMessage());
        }


        s.print();

        System.out.println("=========add");

        try {
            s.find("010");
        } catch (PersonNotFoundException e) {
            System.out.println(e.getMessage());
        }

        System.out.println("=========find");

        try {
            s.update("011",new Employee("044","오채윤","강서","44"));
        } catch (PersonNotFoundException e) {
            System.out.println(e.getMessage());
        }
        System.out.println("=========update");
        try {
            s.delete("010");
        } catch (PersonNotFoundException e) {
            System.out.println(e.getMessage());
        }
        System.out.println("=========delete");

        s.print();

    }
}

 

 

 

결과

 

끝없는 절망

 

 

 

 

자바도 곧 끝나는구나...

728x90