package ex0728;

public class Ex01_exception {
	public static void main(String[] args) {
		User1 ob = new User1();
		
		try {
			ob.set("김자바", -5);
			// ob.set(null, 10);
			System.out.println(ob.getName() + ":" + ob.getAge());
		} catch (Exception e) {
			System.out.println(e.toString());
		}

		
	}
}

class User1 {
	private String name;
	private int age;

	public void set(String name, int age) throws Exception{
		try {
			setName(name);
			setAge(age);
		} catch (Exception e) {
			// System.out.println(e.toString());
			// throw new Exception("값을 설정하지 못했습니다."); // 새로운 예외를 발생
			
			throw e; // 예외를 다시 던짐
		}
		
	}

	public String getName() {
		return name;
	}

	public void setName(String name) throws Exception {
		if(name == null)
			throw new Exception("이름은 null이 될 수 없습니다.");
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) throws Exception {

		if (age < 0)
			throw new Exception("나이는 0이상입니다.");

		this.age = age;
	}

}

package ex0728;

import java.util.Scanner;

public class Ex02_exception {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		User2 ob = new User2();

		try {
			System.out.print("이름 ? ");
			ob.setName(sc.next());
			System.out.print("나이 ? ");
			ob.setAge(sc.nextInt());
			
			System.out.println(ob.getName()+"+"+ob.getAge());
		} catch (Exception e) {
			System.out.println("입력 오류 입니다.");
		} finally { // finally 에서 자원을 닫아주어야 한다.
			sc.close();
		}
		System.out.println("end...");
	}
}

class User2 {
	private String name;
	private int age;

	public String getName() {
		return name;
	}

	public void setName(String name) throws Exception {
		if(name.length()<2)
			throw new Exception("이름은 두자 이상입니다.");
		
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) throws Exception {

		if (age < 0)
			throw new Exception("나이는 0이상만 가능 합니다.");

		this.age = age;
	}

}

 

여기서는 예외가 발생하면 "입력 오류 입니다."를 출력한다. 

예외가 발생했을 때 만들었던 예외를 출력하려면

System.out.println(e.toString()); 이거를 추가해야지 왜 예외가 발생했는지 알려줌.

package ex0728;

import java.util.InputMismatchException;
import java.util.Scanner;

public class Ex03_exception {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		User3 ob = new User3();

		try {
			System.out.print("이름 ? ");
			ob.setName(sc.next());
			System.out.print("나이 ? ");
			ob.setAge(sc.nextInt());
			
			System.out.println(ob.getName()+"+"+ob.getAge());
		} catch (InputMismatchException e) {
			System.out.println("숫자만 입력 가능합니다...");
		} catch (NameValidException e) {
			System.out.println("이름은 두자 이상이어야 합니다...");
		} catch (AgeValidException e2) {
			System.out.println("나이는 0이상 입니다...");
		} catch (Exception e) {
			e.printStackTrace();
		} finally { // finally 에서 자원을 닫아주어야 한다.
			sc.close();
		}
		System.out.println("end...");
	}
}

// 사용자 정의 예외 클래스(checked exception)
class NameValidException extends Exception {
	private static final long serialVersionUID = 1L; // 직렬화

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

class AgeValidException extends Exception {
	private static final long serialVersionUID = 1L;

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

class User3 {
	private String name;
	private int age;

	public String getName() {
		return name;
	}

	public void setName(String name) throws NameValidException {
		if(name.length()<2)
			throw new NameValidException("이름은 두자 이상입니다.");
		
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) throws AgeValidException {

		if (age < 0)
			throw new AgeValidException("나이는 0이상만 가능 합니다.");

		this.age = age;
	}

}

checked exception은 exception의 자식 클래스 이므로 사용자 정의 예외 클래스를 만드려면 Exception을 상속받아서 만들어야 한다. 직렬화의 경우 아직 배우지 않았으나 사용자 정의 예외 클래스를 만들 때는 옆에 느낌표를 눌러서 해결해줘야한다. 

굳이 catch 블록에

System.out.println("이름은 두자 이상이어야 합니다..."); 를 쓰지 않고

System.out.println(e.toString()); 를 넣어서 해도 될 것 같다.

throws
 : 메소드 시그니처(선언부분)에 선언
 : 메소드를 호출하는 곳에서 예외처리를 하도록 설정
 
throw
 : 예외를 강제로 발생 시킴

'쌍용강북교육센터 > 7월' 카테고리의 다른 글

0729_Ex01~Ex05_Generic  (0) 2021.07.29
0728_Ex11~Ex17_generic : 제네릭  (0) 2021.07.29
0727_패키지  (0) 2021.07.27
0727_Ex06~Ex08_enum : 열거형  (0) 2021.07.27
0727_Ex05_중첩 인터페이스  (0) 2021.07.27

+ Recent posts