사용자 정의 예외처리(Custom Exception)

JAVA에서 발생 될 수 있는 다양한 예외처리..

값이 null 객체에 접근시 발생하는 NullPointException..

숫자가 아닌 문자를 숫자로 변환 시 발생하는 NumberFormatException 등..

JAVA에는 다양한 Exception(예외)이 정의되어있다.

또한 미리 정의된 메시지 역시 있지만..

사용자가 필요에 의해 예외를 정의 할 수 있다.

오류가 발생 한 경우 특정 메시지, 코드 등을 정의 하여 반환 하는 경우라 생각한다.

– 사용자 정의 클래스 생성

public class CustomException extends Exception {
	
	private static final long serialVersionUID = 1L;
	
	Exception exception;
	private String message;
	
	public CustomException(String message) {
		this.message = message;
	}
	
	public String getMessage() {
		if(message != null) {
			return message;
		}else {
			return exception.getMessage();
		}
	}
}

Exception.class 를 상속 받아 작성(message 뿐 아니라 코드, 객체 다양하게 추가하여 사용 가능..

 

– 사용하기..

try {
	TestVO testVO= testService.getTestInfo(key);
	ArrayList<TestVO> testList = testService.getTestList(testVO.getKey());
	
	request.setAttribute("testVO", testVO);
	request.setAttribute("testList", testList);
}catch (CustomException custom) {
	request.setAttribute("message", custom.getMessage());
	return ERROR_PAGE;
}catch (Exception e) {
	request.setAttribute("message", e.getMessage());
	return ERROR_PAGE;
}

위와 같이 작성하고 testVO가  null 이면 CustomException 에서

JAVA 기본 예외가 작동할 줄 알았다..

(Exception.class 상속 받았으니까…)

그러나 아무러 작동도 하지 않을 뿐더라..

생성자에 정의한 message 역시 설정 할 수 없다..

또한 아래와 같은 에러 메시지가 발생한다.

try 구문안에 CustomException 을 사용하는 경우가 없기 때문…

getTestInfo 메소드를 정의한 인터페이스에  throws CustomException을 추가

TestVO getTestInfo(String key) throws ErsException;

실제 서비스에서는 CustomException 을 발생시키고

생성자를 이용하여 오류 메시지를 작성한다.

@Override
public TestVO getTestInfo(String key) throws CustomException {
	TestVO testVO = testMapper.getTestInfo(key);
	if(testVO == null) {
		throw new CustomException("정보를 조회 할 수 없습니다.");
	}
	return testVO; 
}

try 구문 안에 해당 예외처리를 발생(throw new CustomException) 시켜줘야 한다.

 

Service 단에서 객체 null 여부를 체크하여 처리하는 방식..

또한

catch (CustomException custom) {
	request.setAttribute("message", custom.getMessage());
	return ERROR_PAGE;
}catch (Exception e) {
	request.setAttribute("message", e.getMessage());
	return ERROR_PAGE;
}

CustomException 에서 catch 할 수 없는 예외를 위해 JAVA 에서 제공하는

Exception 을 추가로 처리하여 발생 할 수 있는 예외를 처리하여 준다.

 

0 글이 마음에 드셨다면 하트 꾸욱~

댓글 남기기

이메일은 공개되지 않습니다. 필수 입력창은 * 로 표시되어 있습니다