본문 바로가기
수업시간 JAVA/이론

Exception만들기/throw 던짐 /throws 위임

by SEOKIHOUSE 2023. 5. 18.

1)exception만들기

throw 예외던짐

throws 예외 위임

 

package practice0518exception만들기;

public class Over100Exception extends Exception{
	
	public Over100Exception(String msg) {
		super(msg);
	}
}

 

package practice0518exception만들기;

public class MinusException extends Exception{
	
	public MinusException(String msg) {
		super(msg);
	}
}
package practice0518exception만들기;

public class ScoreManager {

	public void validScoreRange(int score) throws MinusException, Over100Exception {
		//throws 사용하는쪽에 예외 위임
		if (score < 0) {
			throw new MinusException("음수는 입력할 수 없습니다");
			//MinusException 여기에 예외던짐
		} else if (score > 100) {
			throw new Over100Exception("100점은 초과할 수 없습니다");
		} else {
			System.out.println("정상값 입니다");
		}
	}
}
package practice0518exception만들기;

public class Test {

	public static void main(String[] args)  {
		ScoreManager sm = new ScoreManager();
		try {
			sm.validScoreRange(60);
			sm.validScoreRange(111);
		}catch(MinusException | Over100Exception e) {
			System.out.println(e.getMessage());
		}
	}

}


2)배열 arrayexception연습

package practice0518exception만들기;

public class OutofBoundEx {

	public static void main(String[] args) {
		int []a = new int[3];
		
		try {
			a[0] =1;
			a[1] =1;
			a[2] =1;
			a[3] =1;
		}catch(ArrayIndexOutOfBoundsException e) {
			System.out.println("배열 범위 초과");
			System.out.println("배열에는 " + a.length + "개 데이터만 들어갈 수 있음");
		}
	}

}


3)객체 exception연습

package practice0518exception만들기;

class Student {
	int sno;
	String name;
	int score;
	
	public Student() {
		
	}
	
	public Student(int sno, String name, int score) {
		this.sno = sno;
		this.name= name;
		this.score = score;
	}
	public String toString() {
		return "sno=" + sno + " name=" + name + " score=" + score; 
 	}
}

public class InstanceArrayNullEx {
	public static void main(String[] args) {
		//1번
//		int[] array = new int[3]; 
//		int [] array = {1,2,3}; //배열초기화
		Student[] array = {new Student(),new Student(),new Student()}; //배열초기화
		System.out.println("-------------------");
		//2번
		Student stu01 = new Student(1,"홍길동",20);
		Student[] array1 = {stu01,new Student(2,"짱구",200),new Student(3,"훈이",20)}; //배열초기화
		
		System.out.println("--------------------");
		Student [] students = new Student[3];
		try {
//			students[0] = new Student();
			students[0].sno = 1;
			students[0].name = "홍길동";
			students[0].score = 20;
		}catch(NullPointerException e) {
			System.out.println(e.getMessage());
			System.out.println("객체생성하세요");
		}
		
		
		
	}
}