renz
renz

Reputation: 1070

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

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.

3.System creates new section.

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.

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?

Upvotes: 1

Views: 32258

Answers (3)

Jair Reina
Jair Reina

Reputation: 2915

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(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_Exceptions How to throw a general exception in Java? http://docs.oracle.com/javase/6/docs/api/java/lang/Throwable.html#getMessage()

Upvotes: 3

Jim Garrison
Jim Garrison

Reputation: 86774

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.

Upvotes: 4

Michael
Michael

Reputation: 2500

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:

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().

Upvotes: 1

Related Questions