Java异常:抛出或发送为返回(函数输出)?

Rah*_*hul 2 java exception-handling

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

public void caller {
  try {
      A.createBuilding();
  catch (Exception e) {
      process exception
  }
}
Run Code Online (Sandbox Code Playgroud)

第一种方法:

public class A {
   public String createBuilding throws Exception {
     try {
        blah blah blah
     catch (Exception e) {
        throw new Exception(e);
     }
}
Run Code Online (Sandbox Code Playgroud)

第二种方法:

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;
}
Run Code Online (Sandbox Code Playgroud)

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

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

感谢所有的帮助!

Sur*_*ran 8

使用第一个课程,即使用例外.

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

原因:如果您使用Exceptions,您将能够在围绕Thread.uncaughtExceptionHandler和stack-traces等异常的java构建中利用整个错误处理框架.同样使用excpetion是错误处理的首选方法,建议优先于返回自定义字符串来识别错误