티스토리 뷰

카테고리 없음

[자바] 자바의 try and catch 문?

필살기쓰세요 2020. 12. 30. 17:14

Try 및 catch는 예외를 숨기지 않고 우아하게 처리하는 데 사용됩니다. getinput ()을 호출하는 경우 무언가 잘못되었는지 알고 싶지 않습니까? 숨기고 싶다면 다음과 같이 할 수 있습니다.

public String getInput(String file) {
    StringBuilder ret = new StringBuilder();
        String buf;
            BufferedReader inFile = null;
            
                try {
                        inFile = new BufferedReader(new FileReader(filename));
                                while (buf = inFile.readLine())
                                            ret.append(buf);
                                                } catch (FileNotFoundException e) {
                                                        ret.append("Couldn't find " + file);
                                                            } catch (IOException e) {
                                                                    ret.append("There was an error reading the file.");
                                                                        } finally {
                                                                                if (inFile != null) {
                                                                                           try {
                                                                                                         inFile.close();
                                                                                                                    } catch (IOException aargh) {
                                                                                                                                  // TODO do something (or nothing)
                                                                                                                                             }
                                                                                                                                                     }
                                                                                                                                                         }
                                                                                                                                                         
                                                                                                                                                             return ret.toString();
                                                                                                                                                             }
                                                                                                                                                             

예외를 개별적으로 포착하기를 원한다는 점은 주목할 가치가 있습니다. Exception일부 답변이 제안한대로 맹목적으로 잡는 것은 나쁜 생각입니다. 당신은 당신이 한 일을 처리하기 위해 결코 보지 못한 것을 잡기를 원하지 않습니다. 전혀 보지 못한 예외를 포착하려면 로그를 기록하고 사용자에게 오류를 정상적으로 표시해야합니다.

-------------------

다음은 예외 처리 전략에 대한 좋은 SO 스레드입니다.

내 예외 처리 전략 비판

몇 가지 다른 생각 :

  1. 물건을 잡고 숨기는 데주의하십시오. 이 경우, 호출자에게 뭔가 잘못되었고 거래를 끝낼 수 없다는 것을 알리기 때문에 실제로 "throws"를 사용하는 것이 좋습니다 (유효한 응답 반환). 나는 단지 평범한 "예외"보다는 "IOException을 던진다"라고 말할 것이다. 예외를 잡는 데 신경을 쓰려면 그 예외를 잡기 위해 잡는 것이 아니라 건설적인 일을하십시오.

  2. 파일 I / O를 처리 할 때 try / catch / finally를 사용하고 finally 절에서 파일을 닫을 수 있습니다.

코드가 진행되는 한 @Pablo Santa Cruz를보고 주석을 읽으십시오. 내 코드는 매우 유사합니다.

-------------------
public String getInput(String filename)
{
    BufferedReader infile = null;
        try {
               infile = new BufferedReader (new FileReader(filename));
                      String response = infile.readLine();
                             return response;
                                 } catch (IOException e) {
                                        // handle exception here
                                            } finally {
                                                   try { infile.close(); } catch (IOException e) { }
                                                       }
                                                           return null;
                                                           }
                                                           
-------------------

다음과 같이 작성합니다.

public String getInput(String filename) {
    BufferedReader infile = null;
        String response = "";
            try { 
                    infile = new BufferedReader (new FileReader(filename));
                            response = infile.readLine();
                                } catch( IOException ioe ) {
                                        System.err.printf("Exception trying to read: %s. IOException.getMessage(): %s",
                                                                   filename, ioe.getMessage() );
                                                                       } finally {
                                                                               if( infile != null ) try {
                                                                                           infile.close();
                                                                                                   } catch( IOException ioe ){}
                                                                                                       }
                                                                                                           return response;
                                                                                                           }
                                                                                                           

이 특별한 경우에 예외가 발생하면 빈 문자열 ""이 나에게 좋습니다. 항상 그런 것은 아닙니다.

-------------------

이것은 jcms 답변의 적응입니다-그의 솔루션에서 예외 처리가 마음에 들지 않았기 때문에 그랬습니다 ...

예외가 발생하면 어떻게해야할지 결정해야합니다. 일반적으로 일부 요구 사항에서 다룹니다. 로깅은 좋은 생각이지만 여전히 뭔가를해야합니다. 적어도 파일 내용과 오류 메시지를보고하는 데 반환 값을 사용하지는 않습니다. 수신자를 위해 디코딩하기가 꽤 어렵습니다. 누락 된 파일이나 IO 오류가 예외적 인 상황 인 경우 일반적인 방법으로 예외를 throw 할 수 있습니다. 또는 이것이 제 제안입니다. 파일 내용과 오류 상태를 모두 반환하는 작은 클래스를 정의합니다.

public class FileContent {
  private String fileContent = null;
    private Throwable error = null;
    
      public FileContent(String fileContent, Throwable error) {
          this.error = error;
              this.fileContent = fileContent;      
                }
                
                  // getters for all fields (no setters!)
                  
                    public boolean isValid() {
                        return (error == null);
                          }
                          }
                          

getInput()방법은 다음과 같이 될 것입니다 :

public FileContent getInput(final String fileName) {
    final StringBuilder fileContentBuilder = new StringBuilder();
        String buffer = null;
            BufferedReader reader = null;
                Throwable error = null;
                
                    try {
                            reader = new BufferedReader(new FileReader(fileName));
                                    while (buffer = reader.readLine()) {
                                                fileContentBuilder.append(buffer);
                                                        }
                                                            } catch (FileNotFoundException e) {
                                                                    error = new RuntimeException("Couldn't find " + fileName, e);
                                                                        } catch (IOException e) {
                                                                                error = new RuntimeException("There was an error reading the file.", e);
                                                                                    } finally {
                                                                                            if (inFile != null) {
                                                                                                       try {
                                                                                                                     inFile.close();
                                                                                                                                } catch (IOException e) {
                                                                                                                                              error = new RuntimeException(
                                                                                                                                                                       "Couldn't close reader for file " + fileName, e);
                                                                                                                                                                                  }
                                                                                                                                                                                          }
                                                                                                                                                                                              }
                                                                                                                                                                                              
                                                                                                                                                                                                  return new FileContent(fileContentBuilder.toString(), error);
                                                                                                                                                                                                  }
                                                                                                                                                                                                  
                                                                                                                                                                                                  public void useGetInput() {
                                                                                                                                                                                                     FileContent content = getInput("your/path/to/your/file");
                                                                                                                                                                                                        if (content.isValid()) {
                                                                                                                                                                                                             System.out.println(content.getFileContent());
                                                                                                                                                                                                                } else {
                                                                                                                                                                                                                     content.getError().printStackTrace();
                                                                                                                                                                                                                        }
                                                                                                                                                                                                                        }
                                                                                                                                                                                                                        

(개선 사항 : RuntimeException을 래퍼로 사용하는 대신 자체 예외 유형을 정의 할 수 있음)

-------------------

다음과 같이해야합니다.

public String getinput(String filename) 
{
    BufferedReader infile = null;
        String response = null;
            try {
                    infile = new BufferedReader(new FileReader(filename));
                            response = infile.readLine();
                                } catch (IOException e) {
                                        //handle exception
                                            } finally {
                                                    try {
                                                                if (infile != null)
                                                                              infile.close();
                                                                                      } catch (IOException e) {
                                                                                                  //handle exception
                                                                                                          }
                                                                                                              }
                                                                                                                  return response;
                                                                                                                  }
                                                                                                                  

예외로 인해가 제대로 닫히지 않으면 finallymemleaks로 끝날 수 있으므로 다른 사람이 언급 한대로 절을 추가해야합니다 BufferedReader.



출처
https://stackoverflow.com/questions/1901838
댓글
공지사항
Total
Today
Yesterday
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31