Java 异常:返回还是作为返回发送(函数输出)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7208953/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 19:04:51  来源:igfitidea点击:

Java exception: throw back or send as return (function output)?

javaexception-handling

提问by Rahul

Here's the usage: I am writing classes and functions which are designed to perform a specific function/task (for eg createBuilding, destroyBuilding etc). The design I am following is that the function does not process/handle any error scenario. Its the responsibility of the caller to take an appropriate action, in case there is an error/exception. I can do this in two ways:

这是用法:我正在编写旨在执行特定功能/任务(例如 createBuilding、destroyBuilding 等)的类和函数。我遵循的设计是该函数不处理/处理任何错误情况。如果出现错误/异常,调用者有责任采取适当的行动。我可以通过两种方式做到这一点:

public void caller {
  try {
      A.createBuilding();
  catch (Exception e) {
      process exception
  }
}

First approach:

第一种方法:

public class A {
   public String createBuilding throws Exception {
     try {
        blah blah blah
     catch (Exception e) {
        throw new Exception(e);
     }
}

Second approach:

第二种方法:

public class A {
   public String createBuilding {
     StringBuffer sb = new StringBuffer();
     try {
        blah blah blah
     catch (Exception e) {
        sb.add(e.toString());
     }
     return sb.toString();
}

The user in the second case does the following:
public void caller throws Exception {
      String st = A.createBuilding();
      if (st.contains("Exception"))
        do something;
}

Assume that the called function always returns a string.

假设被调用的函数总是返回一个字符串。

Any comments on which approach is better? Any pitfalls/issues I am overlooking?

关于哪种方法更好的任何评论?我忽略了任何陷阱/问题?

Appreciate all the help!!!

感谢所有的帮助!!!

回答by Suraj Chandran

Use the first one ofcourse, i.e use Exceptions.

使用第一个当然,即使用异常。

The second one breaks years of research on error handling, dont do it.

第二个打破了多年来对错误处理的研究,不要这样做。

Reason: If you use Exceptions you will be able to leverage the entire error-handling framework in java build around exceptions like Thread.uncaughtExceptionHandler and stack-traces etc. Also using excpetion is the preferred way of error handling and will be recommended over returning custom strings to identify errors

原因:如果您使用异常,您将能够利用 Java 中的整个错误处理框架围绕 Thread.uncaughtExceptionHandler 和堆栈跟踪等异常构建。此外,使用 excpetion 是错误处理的首选方式,建议使用返回自定义识别错误的字符串

回答by rsp

Returning a string removes information (like the stacktrace.) If your method does not handle the exception, it should not catch it and let the caller handle it:

返回字符串会删除信息(如堆栈跟踪。)如果您的方法不处理异常,则不应捕获它并让调用者处理它:

   public void createBuilding() throws Exception {

        blahBlahBlah();
   }

回答by Marius Burz

The only disadvantage in using Exceptions is that they are a tiny bit slower, otherwise they only provide advantages (stack traces, possibility to use specialized handlers, easy to use states, built-in etc.). If the performance impact is holding you back using them, you should probably switch to ASM or C, and if you do so, don't forget to return 0 for success and anything else for failure so that you have enough codes for them plenty possible errors ;)

使用异常的唯一缺点是它们有点慢,否则它们只会提供优势(堆栈跟踪、使用专门处理程序的可能性、易于使用的状态、内置等)。如果性能影响阻碍您使用它们,您可能应该切换到 ASM 或 C,如果您这样做,请不要忘记返回 0 表示成功和其他任何失败,以便您有足够的代码供它们使用错误;)

No really, go ahead and use Exceptions by all means. Except if you can come up with a reason lots of other folks can see as valid as well (so not only yourself).

不,继续使用 Exceptions 。除非你能想出一个很多其他人也认为同样有效的理由(不仅仅是你自己)。