2014-01-24 3 views
1

FileUtils 클래스에 일부 유효성 검사를하고 싶습니다. 잘못된 경우 유효성 검사가 실패한 이유에 대한 좋은 오류 메시지를 반환해야합니다. 그래서 나는 가지고있다 :Java - 다른 오류 메시지로 유효성 검사를 설정하는 방법

public static boolean isValidFile(File file) throws Exception 
{ 
    if(something) 
     throw new Exception("Something is wrong"); 
    if(somethingElse) 
     throw new Exception("Something else is wrong"); 
    if(whatever) 
     throw new Exception("Whatever is wrong"); 

    return true; 
} 

public void anotherMethod() 
{ 
    try 
    { 
     if(isValidFile(file)) 
      doSomething(); 
    } catch (Exception e) { 
     displayErrorMessage(e.getMessage()); 
    } 
} 

그러나 이것은 isValidFile 호출이 결코 거짓 일 수 없기 때문에 나에게는 이상한 것처럼 보인다. 또한 if 조건의 순서를 역순으로 바꾸어 코드가 잘못된 경우 빠른 부팅을 수행하면 문제가 더 복잡해집니다. 게다가 오류 메시지를 전달하는 방법으로 예외 처리 코드가있는 것을 좋아하지 않습니다.

public void anotherMethod() 
{ 
    try 
    { 
     if(!isValidFile(file)) 
      return; 
     doSomething(); 
     .. 
     doMoreThings(); 
    } catch (Exception e) { 
     displayErrorMessage(e.getMessage()); 
    } 
} 

에 예외를 사용하지 않고 모든 작업을 수행하고 여전히 당신이 볼처럼 isValidFile() 메서드가 오류 코드가 int를 반환하지 않고 오류가 무엇인지의 표시를 반환 가질 수있는 방법이 있나요 C 등

답변

2

예 : 파일이 유효 수익을 빈 목록 또는 null을 때
그렇지 않으면 검증 문제 목록을 반환,

public static List<String> isValidFile(File file)

에 방법을 변경합니다. 유효성 검사가 실패한 경우
반환 값이 표시됩니다.

0

은 당신이 뭔가를 할 수 있습니다 :

public static String validateFile(File file) 
{ 
    String ret = null; 

    if(something) { 
     ret = "Something is wrong"; 
    } else if(somethingElse) { 
     ret = "Something else is wrong"; 
    } else if(whatever) { 
     ret ="Whatever is wrong"; 
    } 

    return ret; 
} 

public void anotherMethod() 
{ 
    String errorMessage = validateFile(file); 
    boolean fileIsValid = errorMessage == null; 
    if (fileIsValid) { 
     doSomething(); 
    } else { 
     displayErrorMessage(errorMessage); 
    } 
} 

이별로 꽤 있지만,이 일을 가져옵니다.