사용자 정의 예외를 만들려면 Exception클래스나 RuntimeException 클래스를 상속받아야 한다.
또한, 사용자 정의 예외는 JVM에서 예외를 발생시켜 주지 않으므로 직접 예외 객체를 생성해 주어야 한다.
RuntimeException을 상속받으면 마찬가지로 try-catch문이 필수가 아니지만 Exception을 상속받은 사용자 정의 클래스 이면
try-catch문이 강제된다.
예시
public class MyuncheckedExceptoin extends RuntimeException {
private String errMsg;
public MyuncheckedExceptoin(String errMsg) {
super(errMsg);
this.errMsg = "사용자 정의 에러메시지: " + errMsg;
}
public String MygetMessage() {
return this.errMsg;
}
}
public class mycheckedException extends Exception {
private String errMsg;
public mycheckedException(String errMsg) {
super(errMsg);
this.errMsg = "사용자 정의 에러메시지: " + errMsg;
}
public String MygetMessage() {
return this.errMsg;
}
}
'Java' 카테고리의 다른 글
Chained Exception (0) | 2023.05.29 |
---|---|
Exception re-throwing, try-catch문에서의 return (0) | 2023.05.26 |
throw, checked - unchecked 예외, throw (0) | 2023.05.23 |
예외 (0) | 2023.05.22 |
익명 클래스(anonymous class) (0) | 2023.05.18 |