java 如何从构造函数返回错误消息(字符串)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14554054/
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-31 16:38:00  来源:igfitidea点击:

How to return an error message (String) from a constructor?

javaconstructor

提问by renz

Requirements:

要求:

  1. Section is created by selecting one teacher, one subject and one schedule.

  2. System verifies that all business rules are followed.

    • System detects that a business rule is not being followed.

    • System informs user of conflict.

    • System doesn't create new section.

  1. 部分是通过选择一名教师、一门学科和一个时间表来创建的。

  2. 系统验证是否遵循了所有业务规则。

    • 系统检测到未遵循业务规则。

    • 系统通知用户冲突。

    • 系统不创建新部分。

3.System creates new section.

3.系统新建栏目。

My problem is, if I define a constructor for section, Section(Teacher t, Subject s, Schedule c), I don't know how to return the error message for the conflict.

我的问题是,如果我为 Section(Teacher t, Subject s, Schedule c) 部分定义构造函数,我不知道如何返回冲突的错误消息。

Should I just let my constructor throw an exception? If yes, how to return a string from a caught exception? How to create that exception?

我应该让我的构造函数抛出异常吗?如果是,如何从捕获的异常中返回字符串?如何创建该异常?

Or is there any better, yet simple, implementation?

或者有没有更好但更简单的实现?

回答by Jim Garrison

Reporting constructor failure boils down to two options:

报告构造函数失败归结为两个选项:

  1. Throw an exception as you suggest. This is a reasonable approach if failure is not expected to happen often and is truly "exceptional".
  2. If failure is a normal part of the business logic, I'd recommend using the Factory pattern and returning a wrapper object that contains the newly created object plus a status variable that can indicate the detailed causes of the failure when it occurs.
  1. 按照您的建议抛出异常。如果故障不会经常发生并且确实是“异常的”,那么这是一种合理的方法。
  2. 如果失败是业务逻辑的正常部分,我建议使用工厂模式并返回一个包装器对象,该对象包含新创建的对象和一个状态变量,该变量可以指示失败发生时的详细原因。

回答by Jair Reina

You can throw the exception for sure.

您肯定可以抛出异常。

throw new Exception("Some required files are missing");

Or create a new Exception to be used in your app (it will work the same way)

或者创建一个新的异常以在您的应用程序中使用(它将以相同的方式工作)

If you want to read the message inside of a try / catch statement just do this:

如果您想阅读 try / catch 语句中的消息,请执行以下操作:

try
{
  // ...
}
catch(Exception ex)
{
  System.out.println(ex.getMessage()); //this will get "Some required files are missing"
}

For more information checke these links out: http://en.wikibooks.org/wiki/Java_Programming/Throwing_and_Catching_ExceptionsHow to throw a general exception in Java?http://docs.oracle.com/javase/6/docs/api/java/lang/Throwable.html#getMessage()

有关更多信息,请查看以下链接: http://en.wikibooks.org/wiki/Java_Programming/Throwing_and_Catching_Exceptions如何在 Java 中抛出一般异常?http://docs.oracle.com/javase/6/docs/api/java/lang/Throwable.html#getMessage()

回答by Michael

It isn't possible to return a value from a constructor. Your only way to do this is to throw an exception of some sort. You can either use an existing exception type (if there are any applicable) or create your own by extending Exception. For example:

不可能从构造函数返回值。这样做的唯一方法是抛出某种异常。您可以使用现有的异常类型(如果有任何适用)或通过扩展Exception. 例如:

public class MyException extends Exception {

    public MyException(){
        super();
    }

    public MyException(String message){
        super(message);
    }
}

Your constructor would simply throw a new instance of the exception and set an appropriate message. The code creating the class instance would catch the exception and handle it. You can obtain the message at that point by calling getMessage().

您的构造函数将简单地抛出异常的新实例并设置适当的消息。创建类实例的代码将捕获异常并处理它。您可以通过调用获取此时的消息getMessage()