본문 바로가기

DEVELOPER/Java

예외 처리 미루기

반응형

앞에서 정리한 예외 처리 방법에서 추가로 다른 방법이 있다.

그것은 throws를 이용하여 처리를 미루는 방법인데..

다시 말하면 해당 문장에서는 처리를 하지 않고, 해당 메서드를 사용하는 곳에서 처리를 하게 하는 것이다.


 

throws를 사용하는 예제


public class ThrowsExeption {

	public Class loadClass(String fileName, String className) throws FileNotFoundException, ClassNotFoundException {
		
		FileInputStream fis = new FileInputStream(fileName);
		
		Class c = Class.forName(className);
		return c;
	}
	
	public static void main(String[] args) {

		ThrowsExeption test = new ThrowsExeption();
		
		try {
			test.loadClass("a.txt", "abc");
		} catch (FileNotFoundException e) {
			System.out.println(e);
		} catch (ClassNotFoundException e) {
			System.out.println(e);
		} 
		
		System.out.println("end");
		
	}

}
  • 위 코드에서 처리가 필요한 부분에 throws로 처리
  • throws 처리가 된 메서드를 사용할 때 try/catch로 예외 처리 진행

① 찾는 파일이 없을 경우

FileNotFoundException 예외 처리


② 파일은 있으나, 로딩할 클래스가 없을 때

ClassNotFoundException 예외 처리


③ 예외가 발생하지 않은 상황에서, 추가로 뭔지 모를 예외를 핸들링하기 위해 

최상위 클래스 Exception을 활용하여 default 처리를 해준다.

public static void main(String[] args) {

	ThrowsExeption test = new ThrowsExeption();
		
	try {
			test.loadClass("a.txt", "java.lang.String");
	} catch (FileNotFoundException e) {
			System.out.println(e);
	} catch (ClassNotFoundException e) {
			System.out.println(e);
	} catch(Exception e) {
                                         //default 처리
	}
		
	System.out.println("end");
		
}
  • 단, default 처리는 블록 맨 마지막 위치해야 한다.

사용자 정의 예외 클래스


  • 자바에서 제공되는 예외 클래스 외에 프로그래머가 직접 만들어야 하는 예외가 있을 경우
  • 기존 예외 클래스 중 가장 유사한 예외 클래스에서 상속 받아 사용자 정의 예외 클래스를 생성
  • 기본적으로 Exception 클래스 상속해서 만들 수 있음

패스워드에 대한 예외 처리

가정

  1. 비밀번호는 null일 수 없습니다.
  2. 비밀번호의 길이는 5 이상 입니다.
  3. 비밀번호는 문자로만 이루어져서는 안됩니다.(하나 이상의 숫자나 특수 문자를 포함)

 

문제의 원인을 메시지로 나타내는 예외 클래스 정의

public class PasswordException extends Exception {
	
	public PasswordException(String message) {
		super(message);
	}
}

 

public class PasswordTest {

		private String password;
		
		public String getPassword(){
			return password;
		}
		
		public void setPassword(String password) throws PasswordException{
			
			if(password == null){
				throw new PasswordException("비밀번호는 null 일 수 없습니다");
			}
			else if( password.length() < 5){
				throw new PasswordException("비밀번호는 5자 이상이어야 합니다.");
			}
			else if (password.matches("[a-zA-Z]+")){
				throw new PasswordException("비밀번호는 숫자나 특수문자를 포함해야 합니다.");
			}
			
			this.password = password;
		}
		
		public static void main(String[] args) {

			PasswordTest test = new PasswordTest();
			String password = null;
			try {
				test.setPassword(password);
				System.out.println("오류 없음1");
			} catch (PasswordException e) {
				System.out.println(e.getMessage());
			}
			
			password = "abcd";
			try {
				test.setPassword(password);
				System.out.println("오류 없음2");
			} catch (PasswordException e) {
				System.out.println(e.getMessage());
			}
			
			password = "abcde";
			try {
				test.setPassword(password);
				System.out.println("오류 없음3");
			} catch (PasswordException e) {
				System.out.println(e.getMessage());
			}
			
			password = "abcde#1";
			try {
				test.setPassword(password);
				System.out.println("오류 없음4");
			} catch (PasswordException e) {
				System.out.println(e.getMessage());
			}
		}
}

각 오류에 대한 결과

반응형

'DEVELOPER > Java' 카테고리의 다른 글

I/O 스트림 정의  (0) 2021.05.09
자바의 예외 처리 - 로그 남기기(log)  (0) 2021.05.09
Java의 예외 처리하기 - Exception  (0) 2021.05.07
reduce( ) 연산  (0) 2021.05.07
스트림(Stream)  (0) 2021.05.06