본문 바로가기
수업(국비지원)/Java

[Java] chap9 : 예외처리 - Exception6(오버라이딩에서 예외처리), Exception7(예외클래스 생성)

by byeolsub 2023. 4. 16.
  • 오버라이딩에서 예외처리

📌

package chap9;
/*
 * 오버라이딩에서의 예외처리: 
 *  부모클래스의 예외처리와 같거나 작은범위(하위예외객체) 가능. 
 */
class Parent {
	public void method() throws RuntimeException {
		System.out.println("Parent 클래스의 method()");
	}
}
class Child extends Parent {
	public void method() throws ArithmeticException {
		System.out.println("Child 클래스의 method()");
	}
}
public class ExceptionEx6 {
	public static void main(String[] args) {
		Child c = new Child();
		c.method();
	}
}

  • 예외클래스 생성

📌

package chap9;

import java.util.Scanner;

public class ExceptionEx7 {
	public static void main(String[] args) {
		try {
			String id= "hong";
			String pw = "1234";
			Scanner scan = new Scanner(System.in);
			System.out.println("id를 입력하세요");
			String inId = scan.next();
			System.out.println("비밀번호를 입력하세요");
			String inPw = scan.next();
			if(id.equals(inId) && pw.equals(inPw)) {
				System.out.println("로그인 성공");
			} else if(!id.equals(inId)) {
				throw new LoginFailException("ID 확인하세요");
			} else {
				throw new LoginFailException("비밀번호를 확인하세요");
			}
		} catch (LoginFailException e) {
			System.out.println(e.getMessage());
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
}
class LoginFailException extends Exception{
	LoginFailException(String msg) {
		super(msg);
	}
}