728x90
직접 만드는 예외
예외를 직접 발생시킬 경우 키워드 throw를 활용한다.
public static void main(String[] args) throws Exception {
throw new Exception("예외 강제 발생");
}
package kr.or.ksmart;
class MyExecption extends Exception {
public MyExecption() {
super();
}
public MyExecption (String msg) {
super(msg + " < My 클래스의 필수값 누락 MyExecption ");
}
}
class My {
private String name;
public My(String name) throws MyExecption {
if(name == null || "".equals(name)) {
throw new MyExecption(name + "인수값 null이나 공백");
}
}
public void setMyAge(int age) throws MyExecption {
if(age == 0) {
throw new MyExecption("age 값이 0");
}
}
}
public class Exception03 {
public static void main(String[] args) {
My my = null;
try {
//my = new My(""); <- 생성자 메서드에서 공백 혹은 null일때 예외 발생
my = new My("홍길동");
} catch (MyExecption e) {
e.printStackTrace();
}
try {
my.setMyAge(0); // 0값일 경우 강제 예외 발생
} catch (MyExecption e) {
e.printStackTrace();
}
}
}
package kr.or.ksmart;
class MemberException extends Exception {
public MemberException (){
super();
}
public MemberException (String msg) {
super(msg + " <- MemberException.java 필수정보 누락 예외;");
}
}
class Member {
private String userName;
public void setUserName (String userName) throws MemberException {
if(userName == null || "".equals(userName)) {
throw new MemberException (" <- userName의 값이 null이거나 공백; ");
}
}
}
public class ExceptionEx01 {
public static void main(String[] args) {
try {
Member member = new Member();
member.setUserName("");
} catch (MemberException e) {
e.printStackTrace();
}
}
}
반응형
'Backend > JAVA' 카테고리의 다른 글
객체지향 설계 5대 원칙 - SOILD 원칙 (1) | 2020.07.01 |
---|---|
JAVA - Generic (0) | 2020.05.22 |
JAVA 예외처리하기 RuntimeException (0) | 2020.05.20 |
MVC Servlet - controller 작성하기 - Filter (0) | 2020.05.14 |
Connection Pool 설정하기 (0) | 2020.05.14 |
댓글