简体   繁体   English

尝试捕获Java中的语句?

[英]try and catch statements in java?

how can i rewrite the following method using try and catch statements instead of the throws clause in the method header: 我如何使用try和catch语句而不是方法标题中的throws子句重写以下方法:

public String getInput(String filename) throws Exception
{
    BufferedReader infile = new BufferedReader (new FileReader(filename));
    String response = infile.readLine();
    infile.close();

    return response:
}

Try and catch are used to gracefully handle exceptions, not hide them. 尝试和捕获用于优雅地处理异常,而不是隐藏它们。 If you are calling getinput() wouldn't you want to know if something went wrong? 如果您正在调用getinput(),您是否想知道是否出了问题? If you wanted to hide it I suppose you could do something like 如果您想隐藏它,我想您可以做些类似的事情

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();
}

It's worth noting that you want to be catching the exceptions individually. 值得注意的是,您想单独捕获异常。 Blindly catching Exception as some answers have suggested is a bad idea. 正如一些答案所建议的那样,盲目地捕获Exception是一个坏主意。 You don't want to catch things you never saw coming to handle something you did. 您不想捕捉从未见过的事情来处理您所做的事情。 If you want to catch exceptions you never saw coming you need to log it and gracefully display an error to the user. 如果您想捕获异常,而您从未见过,则需要对其进行记录并向用户优雅地显示错误。

Here's a good SO thread on exception handling strategy: 这是一个关于异常处理策略的优秀SO线程:

Critique my exception handling strategy 批判我的异常处理策略

A couple other thoughts: 还有一些其他想法:

  1. Be careful about catching things and hiding them. 注意捕捉并隐藏它们。 In this case, I would say it's actually better to use "throws" because you're informing the caller of your method that something went wrong and you couldn't keep up your end of the bargain (returning a valid response). 在这种情况下,我想说的是使用“ throws”实际上更好,因为您是在向方法的调用者通知发生了问题,并且您无法跟上讨价还价(返回有效的响应)。 Though I would say "throws IOException" rather than just plain old "Exception". 尽管我会说“引发IOException”,而不只是普通的“ Exception”。 If you're going to bother catching the exception, do something constructive with it, don't just catch it for the sake of catching it. 如果您要麻烦捕获异常,请对其进行一些建设性的操作,不要仅仅为了捕获它而捕获它。

  2. You might want to use a try/catch/finally when you're dealing with file I/O and close your file in the finally clause. 在处理文件I / O时,可能需要使用try / catch / finally,并在finally子句中关闭文件。

As far as the code goes, look at @Pablo Santa Cruz's and read the comments. 就代码而言,请查看@Pablo Santa Cruz并阅读注释。 My code would be pretty similar. 我的代码将非常相似。

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;
}

Something like this should do it: 这样的事情应该做到:

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;
}

Note you should add the finally clause as stated by others, as you might end up with memleaks if the BufferedReader is not closed properly, because of an exception. 请注意,您应该添加其他人声明的finally子句,因为如果由于异常而导致BufferedReader未正确关闭,则可能会导致记忆泄漏。

I would write it like this: 我会这样写:

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;
}

In this particular case, if the exception is thrown the empty string "" is good for me. 在这种特殊情况下,如果引发异常,则空字符串""对我有好处。 This is not always the case. 这并非总是如此。

This is an adaptation of jcms answer - did it because I didn't like the exception handling in his solution... 这是jcms答案的改编-这样做是因为我不喜欢他的解决方案中的异常处理...

We have to decide what to do in case of an exception. 如果发生异常,我们必须决定要怎么做。 That's usually covered in some requirements. 通常在某些要求中涵盖了这一点。 Logging is a good idea, but we still have to do something. 记录是一个好主意,但我们仍然必须做一些事情。 At least I'd never use the return value to report file content as well as error messages. 至少我永远不会使用返回值来报告文件内容以及错误消息。 That's pretty hard to decode for the receiver. 对于接收器而言,这很难解码。 One could throw an exception - the usual way, if a missing file or an IO error is an exceptional situation. 如果文件丢失或IO错误是一种例外情况,则可能会引发异常-通常的方式。 Or, and that's my suggestion, we define a small class to return both file content and error state: 或者,这就是我的建议,我们定义一个小类以返回文件内容和错误状态:

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);
  }
}

and the getInput() method will be like this: 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();
   }
}

(Improvements; instead of using RuntimeException as a Wrapper, we could define our own exception type) (改进;我们可以定义自己的异常类型,而不是使用RuntimeException作为包装器)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM