728x90
JAVA Exception 사용자 예외처리
String getMessage() : 예외 객체가 가지고 있는 에러 메시지 반환
void printStackTrace() : 예외 발생 원인과 경로를 추적하여 콘솔에 표시, 디버깅 목적
사용자 정의 예외에서는 throws 대신 throw를 사용한다.
사용자 정의 예외는 예외 객체를 만든 후에 throw라는 키워드를 이용해 예외를 던져줘야 한다.
Exception으로부터 상속받으면 예외 메시지를 담을 수 있는 속성이 있다.
<사용자 예외 클래스 정의>
public class UserException extends Exception{
private int port = 772;
public UserException(String msg){
super(msg); // exception 클래스로부터 파생되어 super에 넣기
}
public UserException(String msg, int port){
super(msg); // exception 클래스로부터 파생되어 super에 넣기
this.port = port;
}
public int getPort(){
return port;
}
}
<사용자 예외 클래스 실행>
public class UserExceptionTest {
public void test1(String[] n) throws UserException {
if(n.length<1)
throw new UserException("아무것도 없다네"); // 객체를 생성해 throw
else
throw new UserException("최종 예선", 703); // 객체를 생성해 throw
}
public static void main(String[] args) {
UserExceptionTest ut = new UserExceptionTest(); // Test 객체 생성
String[] s = new String[2];
s[0] = new String("오모");
s[1] = new String("모오");
try{ // main에서 객체를 생성하고 test 함수를 불러와 try~catch문을 수행한다
ut.test1(args);
}
catch(UserException ue){
ue.printStackTrace(); // 원인과 경로 출력
}
try{ // 한번에 처리하지 않고 나눠서 처리한다
ut.test1(s);
}
catch(UserException ue){
ue.printStack Trace(); // 원인과 경로 출력
}
}
}
728x90
'JAVA Programming > JAVA 개념 정리' 카테고리의 다른 글
JAVA Synchronized 스레드 동기화 (0) | 2024.04.02 |
---|---|
JAVA 제네릭 타입 컬렉션 클래스 (1) | 2021.12.05 |
JAVA Exception 예외 처리 (0) | 2021.12.03 |
JAVA interface 인터페이스 abstract class 추상 클래스 (0) | 2021.12.02 |
JAVA 상속과 다형성 (0) | 2021.12.01 |