Reputation: 1070
Requirements:
Section is created by selecting one teacher, one subject and one schedule.
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
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
Reputation: 86774
Reporting constructor failure boils down to two options:
Upvotes: 4
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