Java: pass error by boolean, null pointer or exception? - java

I think this is an easy but important question.
I am writing a class with a function:
public MyClass myFunction(MyClass mc) { ... }
In this function, it changes some state of mc and return it back. I understand it is not necessary as mc is change in place. The reason why I want to return MyClass is to use null to indicate an failed update.
I could potentially change the return type to boolean and use false to indicate an error:
public boolean myFunction(MyClass mc) { ... }
But I remember I have read an article quite long time ago saying this is not a good practice (although I forgot the detail and why).
I could certainly use exception to represent an error:
public void myFunction(MyClass mc) throws MyException { ... }
But I get a feeling this is too heavy weighted.
My personally opinion is that if the error is meaningful system wide, then exception should be used. If the error is only meaningful for the caller and the function, then exception should not be used. But shall I use null or false to indicate the error in this case?
What is the best practice do you think? Please let me know your opinion.
Many thanks.

Is the failure an expected part of the update process? Or is it something that only happens when it all goes disastrously wrong?
If it is a truly exceptional condition, then you should prefer to use an exception. Return values for this sort of thing tends to get ignored (just look at some of the terrible boolean returning File functions, like mkdirs)
If failure is an expected part of trying to do an update, then you should return either a boolean or some sort of status object.

The practice that's generally frowned upon is using some sort of return code (an int or such) in lieu of throwing an exception. If a failed update is a "normal" behavior, returning a boolean is fine. Collection.add does this, for instance.

From three options you listed, I would not use first one.
public MyClass myFunction(MyClass mc) { ... }
In this case, myFunctions either returns it's parameter (mc) or returns null - only two options are available, so it's basically same as
public boolean myFunction(MyClass mc) { ... }
As Steven Schlansker said, you should decide whether failed update is really exceptional state or something expected which should be handled by user.
One additional thing to note: if you decide to implement it as method returning boolean (not throwing exception) then I would suggest you may sure that no change or all changes are done to MyClass mc object.
For example if myFunction is supposed to update 3 fields (x,y,z) in MyClass. If you call myFunction(mc) and it's able to update two of them (x,y) and fails when updating third (z), then it returns false. Your MyClass mc object is then in inconsistent state, because x and z were updated, but z was not. This may cause further problems if user decides to keep using existing mc object. If you decide to implement myMethod as method trowing exception, it may easier to understand that object may be in invalid state.

It depend on the caller function.
If caller function need the value of that object
then you should return Null in case of failure
and return the OBJECT in case of success
If caller function need only the status of object whether it is updated or not
then return true in case of success
and return false in case of failure

Related

Is it good programming to have a return type of Exception?

I ran into an odd situation during a use case on a project: ESQL is calling a java method, sending it a String input parameter which the method will unmarshal, apply some logic, and then store useful info from the unmarshalled object. So, the method must either throw a JAXBException, or use a try catch in order to handle the possible exceptions.
The problem with this is, that ESQL cannot invoke a java method which includes a throws in the signature. BUT, we want any errors to fall through back to the previously calling MBNode so it can be handled appropriately there, so then trycatch is out of the picture.
It struck me that hey, is it not possible to return a type of Exception when we encounter an issue, and null if not? So I wrote a simple method doing so, and though I didn't get any warnings or errors, it seemed just wrong to me in the sense of good programming.
For example:
public Exception doStuffAndCheckForErorrs(String inString)
{
if(inString.equals(null))
{
return new Exception("Your string is null");
}
else
return null;
}
But I just get a terrible feeling about doing anything this way.
I'm open to any thoughts or different solutions to this, especially if there's a way around the ESQL signature issue.
UPDATE:
Adding reference as to why the ESQL procedure cannot call a java method with a throws clause in the signature.
Excerpt from This link under the CREATE PROCEDURE statement section:
"Any Java method that you want to invoke must have the following basic signature:
public static (< 0 - N parameters>)
where must be in the list of Java IN data types in the table in ESQL to Java data type mapping (excluding the REFERENCE type, which is not permitted as a return value), or the Java void data type. The parameter data types must also be in the ESQL to Java data type mapping table. In addition, the Java method is not allowed to have an exception throws clause in its signature."
This isn't really a question about Java, it's a question about ESQL.
ESQL is able to cope with Java exceptions being thrown through the JNI into ESQL code, you should get a BIP2917 error.
I initially though this might have been an issue with the ESQL method resolver but on IIB v9 I was able to succesfully call the following method:
public static void sayHello() throws Exception{
System.out.println("hello");
}
This makes me think that perhaps you got something else wrong with your ESQL external function/procedure definition?
The point here is you can't DECLARE an exception will be thrown; you can still throw a RuntimeException - without adding a throws clause.
So if you wrap your JAXBException into a RuntimeException, you can throw it and handle according to your requirements, without breaking either requirement. Not sure if I would do that; I would not like to return an exception-type though as it's not meant to be used as a return code.
Be extra sure that this asynch way of handling the issue won't break the ESQL library, as you'll be bypassing part of their code, possibly leaving part of it hanging.
Returning Exception is "quick and dirty". It can be very powerful and useful but this should be avoid if possible.
The invocation in ESQL are made like this for a good reason i won't explained here but you can bypass it by using RuntimeException that does not appears in the method definition.
A use case that specifies throwing an Exception sounds like it may be poorly written.
What is the business or architectural reason for throwing an Exception?
An alternative would be throw a RuntimeException or a custom subclass.
That would allow you to leave it out of the method signature.
Again, the use case seems odd.
The straightforward answer to your question is:
No, it isn't good programming to have a return type of Exception.
The mechanism is meant to happen when something goes wrong, therefore a return type of Exception means that you want to receive the consequence of something that went wrong.
I understand that you can't throw Exception, so you should handle the case with other approach.
The boolean aproach is fine when you want to check up some work: good = return true, bad= return false.
The encapsulation of values in an Object is meant when you want to grab the results of the work: good = return new YourResultObject(val1, val2, ..., valx), bad = return null.
What you can do is use return codes like C programs used to do to report about their states.
Alternatively you can also create an Enum and return the Enum, both are more flexible than the Boolean approach if you want to differentiate between different types of errors
public Enum ReturnCodes {
SUCCESS,
NULLSTRING,
...,
OTHERERROR,
}

Methods returning values vs. those which don't

When you write methods you almost always have to check for things that must be valid.
Lets say you need to throw an IllegalArgumentException if the price argument on a method is invalid. Because I want to break my programs into small pieces I make a private method for it. However is it best practice to create a method that is named something like validatePrize and returns a boolean which I then check in an if statement where I invoke the validatePrize method, and then throw an IllegalArgumentException?
Or is it better that the method does not return anything and also throws the exception?
I would say the answer to this is mainly based on preference. If you want a reusable function which doesn't throw an exception when called, then pick the validatePrize with a boolean return. If you are only using it to check for an exception, then use the validatePrize which throws an exception. In this case I would say that the validatePrize which throws an exception would be more suited, as it can be used for exception handling from outside the class itself.
It totally depends.
Firstly, validatePrize doesn't sound like a boolean method, so IMO it shouldn't return anything.
If you have a bunch of guard clauses, throw an exception. If you need validation across the app for the same collection of attributes, make it a method–but that method can also be used as part of the guard.
Since you already know that a negative value is an invalid argument, you can guard against it by doing :
if(val < 0)
{
return false;
}
I've read in books that guarding against such a situation is the best way to go. It isn't or doesn't meet "an exception criteria". So yeah I would just return a boolean.
Some like to throw exceptions though, but it is up to you.
If you do delegate the check to a method, you could as well throw an exception from that method directly to avoid clutter code in your constructor. This is a typical approach used by guava's Preconditions:
this.value = Preconditions.checkNotNull(value, "value must not be null");
this line will throw an NullPointerException with the associated message if the argument is null. If the argument is not null, it returns the argument which enables to check and assign the argument in one line.
If you are interested, this is what the code looks like:
public static <T> T checkNotNull(T reference, Object errorMessage) {
if (reference == null) {
throw new NullPointerException(String.valueOf(errorMessage));
}
return reference;
}
You could use a similar approach for your use case.
My own opinion about this is that exceptions should only be thrown if something in unexpected. A null pointer can be this, or a negative number for an ID (which should always be positive). Basically, an exception is used to show a problem inside your program. If you're simply validating a user's input, use booleans and tests.

Should we always check each parameter of method in java for null in the first line?

Every method accepts a set of parameter values. Should we always validate the non-nullness of input parameters or allow the code to fail with classic RunTimeException?
I have seen a lot of code where people don't really check the nullness of input parameters and just write the business logic using the parameters. What is the best way?
void public( String a, Integer b, Object c)
{
if( a == null || b == null || c == null)
{
throw new RunTimeException("Message...");
}
.....business logic.....
}
The best way is to only check when necessary.
If your method is private, for example, so you know nobody else is using it, and you know you aren't passing in any nulls, then no point to check again.
If your method is public though, who knows what users of your API will try and do, so better check.
If in doubt, check.
If the best you can do, however, is throw a NullPointerException, then may not want to check. For example:
int getStringLength(String str) {
return str.length();
}
Even if you checked for null, a reasonable option would be throwing a NullPointerException, which str.length() will do for you anyways.
No. It's standard to assume that parameters will not be null and that a NullPointerException will be thrown otherwise. If your method allows a parameter to be null, you should state that in your api.
It's an unfortunate aspect of Java that references can be null and there is no way to specify in the language that they are not.
So generally yes, don't make up an interpretation for null and don't get into a situation where an NPE might be thrown later.
JSR305 (now inactive) allowed you to annotate parameters to state that they should not be given nulls.
void fn(#Nonnull String a, #Nonnull Integer b, #Nonnull Object c) {
Verbose, but that's Java for you. There are other annotation libraries and checkers that do much the same, but are non-standard.
(Note about capitalisation: When camel-casing words of the form "non-thing", the standard is not to capitalise the route word unless it is the name of a class. So nonthing and nonnull.)
Annotations also don't actually enforce the rule, other than when a checker is run. You can statically include a method to do the checking:
public static <T> T nonnull(T value) {
if (value == null) {
throwNPE();
}
return value;
}
private static void throwNPE() {
throw new NullPointerException();
}
Returning the value is handy in constructors:
import static pkg.Check.nonnull;
class MyClass {
#Nonnull private final String thing;
public MyClass(#Nonnull String thing) {
this.thing = nonnull(thing);
}
...
I don't see a great deal of point in doing this. You're simply replicating behaviour that you'd get for free the first time you try to operate on a, b or c.
It depends if you expect any of your arguments to be null - more precisely, if your method can still make a correct decision if some parameters are null.
If not, it's good practice to check for null and raise an exception, because otherwise you'll get a NullPointerException, which you should never catch, as its appearance always indicates that you forgot to check your variables in your code. (and if you catch it, you might miss other occurrences of it being thrown, and you may introduce bugs).
On the other hand, if you throw RunTimeException or some other custom exception, you could then handle it somewhere on the upstream, so that you have more control over what goes on.
Yes, public methods should scrub the input, especially if bad input could cause problems within your method's code. It's a good idea to fail fast; that is, check as soon as possible. Java 7 added a new Objects class that makes it easy to check for null parameters and include a customized message:
public final void doSomething(String s)
{
Objects.requireNonNull(s, "The input String cannot be null");
// rest of your code goes here...
}
This will throw a NullPointerException.
Javadocs for the Objects class: http://docs.oracle.com/javase/7/docs/api/java/util/Objects.html
It depends on what your code is trying to do and the situation in which you want to throw an Exception. Sometime you will want your method to always throw an Exception if your method will not be able to work properly with null values. If your method can work around null values then its probably not necessary to throw an Exception.
Adding too many checked Exceptions can make for very convoluted and complicated code. This was the reason that they were not included in C#.
No, you shouldn't do that universally.
My preferences, in order, would be:
Do something sensible with the null. The sensible thing to do depends entirely on the situation, but throwing a custom exception should not be your first choice.
Use an assertion to check for null and test thoroughly, eliminating any situations in which null input is produced since - a.k.a bugs.
For public APIs, document that null isn't allowed and let it fail with an NPE.
You should never throw a runtime exception unless it is truly a fatal condition for the operation of the system, such as missing critical runtime parameters, but even then this is questionable as the system should just not start.
What are the business rules? Is null allowed for the field? Is it not?
In any case, it is always good practice to CHECK for nulls on ANY parameters passed in before you attempt to operate on them, so you don't get NullPointerExceptions when someone passes you bad data.
If you don't know whether you should do it, the chances are, you don't need to do it.
JDK sources, and Joshua Bloch's book, are terrible examples to follow, because they are targeting very different audiences. How many of us are writing public APIs for millions of programmers?

Is this an Exception Handling abuse?

I have this method, that can return three different response.
At first, it was supposed just only return two, so I make its return type to Boolean
like:
public static boolean isLoteWaitingForImage()
And some business logic came out with that it can has another result, so the method was modified to
public static boolean isLoteWaitingForImage() throws ImageNotPendingException
If a certain select return a null value, but one row its return true, if its not null i will return false. If no row was acquired from the select I will throw an ImageNotPendingException cause it doesn't apply for the given filters in the where clause.
Also thought about doing it in this Way, I have this new Class with the types that are valid to return from the method isLoteWaitingForImage(), with 3 constants properties called:
public class LoteResponse {
public static int VALID = 1;
public static int INVALID = 2;
public static int NO_IMAGE_PENDING = 3;
}
So I will have this new method:
public static int isLoteWaitingForImage() {
return LoteResponse.VALID;
}
Having this on table, I have these two questions:
Any "other" idea about how to accomplish this needing?
Which method is a better practice?
Yes, that looks like an abuse to me.
It would be reasonable to throw the exception if the method simply shouldn't be called when no image is pending. Can the client always know that? Does it represent a bug, or something else going badly wrong for them to be calling it in that state? If not, don't use an exception.
It looks to me like you need an enum.
public enum LoteResponseState
{
Valid,
Invalid,
NoImagePending;
}
public static LoteResponseState getLoteState()
{
...
}
If you expect the code that calls isLoteWaitingForImage() to be directly responsible for handling the "no image pending" condition as well as the others, then use the multiple return values, but use an enum, not ints!
If the "no image pending" condition cannot be usefully handled by the immediate calling code and instead would usually be handled higher up the call stack, then the exception is the better option.
I definitely agree that an enum is the best choice.
As a general rule, if a certain operation is not considered a serious error that will rarely occur, you should not throw an exception. Throw exceptions only for errors that the current method cannot have any way of handling in a useful way, but not as a typical return value.
I am no expert so don't take this as a best-practice advice, but I think using exceptions in this particular case seems like an overkill. I would go for some simple return values as mentioned above.
If you really want to keep track of the situation, for whatever debugging or developing reason, you could perhaps throw RuntimeException("why a runtime exception is thrown") instead. Writing an own Exception seems too excessive if you are not doing something particular with the exception.
I hope that makes some sense. :)
Go for the exception way. It does have a more explicit interface to the caller. If the caller needs to process this ImageNotPendingException make it an Checked Exception.
Returning enum is a bizarre thing as it diminishes encapsulation by delegating business detail and processing to the caller. This way the caller needs to know way too much of the calee.
Sorry about my bad english.

Should a retrieval method return 'null' or throw an exception when it can't produce the return value? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I am using java language,I have a method that is supposed to return an object if it is found.
If it is not found, should I:
return null
throw an exception
other
Which is the best practise or idiom?
If you are always expecting to find a value then throw the exception if it is missing. The exception would mean that there was a problem.
If the value can be missing or present and both are valid for the application logic then return a null.
More important: What do you do other places in the code? Consistency is important.
Only throw an exception if it is truly an error. If it is expected behavior for the object to not exist, return the null.
Otherwise it is a matter of preference.
As a general rule, if the method should always return an object, then go with the exception. If you anticipate the occasional null and want to handle it in a certain way, go with the null.
Whatever you do, I highly advise against the third option: Returning a string that says "WTF".
If null never indicates an error then just return null.
If null is always an error then throw an exception.
If null is sometimes an exception then code two routines. One routine throws an exception and the other is a boolean test routine that returns the object in an output parameter and the routine returns a false if the object was not found.
It's hard to misuse a Try routine. It's real easy to forget to check for null.
So when null is an error you just write
object o = FindObject();
When the null isn't an error you can code something like
if (TryFindObject(out object o)
// Do something with o
else
// o was not found
I just wanted to recapitulate the options mentioned before, throwing some new ones in:
return null
throw an Exception
use the null object pattern
provide a boolean parameter to you method, so the caller can chose if he wants you to throw an exception
provide an extra parameter, so the caller can set a value which he gets back if no value is found
Or you might combine these options:
Provide several overloaded versions of your getter, so the caller can decide which way to go. In most cases, only the first one has an implementation of the search algorithm, and the other ones just wrap around the first one:
Object findObjectOrNull(String key);
Object findObjectOrThrow(String key) throws SomeException;
Object findObjectOrCreate(String key, SomeClass dataNeededToCreateNewObject);
Object findObjectOrDefault(String key, Object defaultReturnValue);
Even if you choose to provide only one implementation, you might want to use a naming convention like that to clarify your contract, and it helps you should you ever decide to add other implementations as well.
You should not overuse it, but it may be helpfull, espeacially when writing a helper Class which you will use in hundreds of different applications with many different error handling conventions.
Use the null object pattern or throw an exception.
Advantages of throwing an exception:
Cleaner control flow in your calling code. Checking for null injects a conditional branch which is natively handled by try/catch. Checking for null doesn't indicate what it is you're checking for - are you checking for null because you're looking for an error you're expecting, or are you checking for null so you don't pass it further on downchain?
Removes ambiguity of what "null" means. Is null representative of an error or is null what is actually stored in the value? Hard to say when you only have one thing to base that determination off of.
Improved consistency between method behavior in an application. Exceptions are typically exposed in method signatures, so you're more able to understand what edge cases the methods in an application account for, and what information your application can react to in a predictable manner.
For more explanation with examples, see: http://metatations.com/2011/11/17/returning-null-vs-throwing-an-exception/
Be consistent with the API(s) you're using.
Just ask yourself: "is it an exceptional case that the object is not found"? If it is expected to happen in the normal course of your program, you probably should not raise an exception (since it is not exceptional behavior).
Short version: use exceptions to handle exceptional behavior, not to handle normal flow of control in your program.
-Alan.
it depends if your language and code promotes:
LBYL (look before you leap)
or
EAFP (easier to ask forgiveness than permission)
LBYL says you should check for values (so return a null)
EAFP says to just try the operation and see if it fails (throw an exception)
though I agree with above.. exceptions should be used for exceptional/error conditions, and returning a null is best when using checks.
EAFP vs. LBYL in Python:
http://mail.python.org/pipermail/python-list/2003-May/205182.html
(Web Archive)
Exceptions are related to Design by Contract.
The interface of an objects is actually a contract between two objects, the caller must meet the contract or else the receiver may just fail with an exception. There are two possible contracts
1) all input the method is valid, in which case you must return null when the object is not found.
2) only some input is valid, ie that which results in a found object. In which case you MUST offer a second method that allows the caller to determine if its input will be correct. For example
is_present(key)
find(key) throws Exception
IF and ONLY IF you provide both methods of the 2nd contract, you are allowed to throw an exception is nothing is found!
I prefer to just return a null, and rely on the caller to handle it appropriately. The (for lack of a better word) exception is if I am absolutely 'certain' this method will return an object. In that case a failure is an exceptional should and should throw.
Depends on what it means that the object is not found.
If it's a normal state of affairs, then return null. This is just something that might happen once in an while, and the callers should check for it.
If it's an error, then throw an exception, the callers should decide what to do with the error condition of missing object.
Ultimately either would work, although most people generally consider it good practice to only use Exceptions when something, well, Exceptional has happened.
Here are a couple more suggestions.
If returning a collection, avoid returning null, return an empty collection which makes enumeration easier to deal with without a null check first.
Several .NET API's use the pattern of a thrownOnError parameter which gives the caller the choice as whether it is really an exceptional situation or not if the object is not found. Type.GetType is an example of this. Another common pattern with BCL is the TryGet pattern where a boolean is returned and the value is passed via an output parameter.
You could also consider the Null Object pattern in some circumstances which can either be a default or a version with no behaviour. The key is avoid null checks throughout the code base. See here for more information Link
In some functions I add a parameter:
..., bool verify = true)
True means throw, false means return some error return value. This way, whoever uses this function has both options. The default should be true, for the benefit of those who forget about error handling.
Return a null instead of throwing an exception and clearly document the possibility of a null return value in the API documentation. If the calling code doesn't honor the API and check for the null case, it will most probably result in some sort of "null pointer exception" anyway :)
In C++, I can think of 3 different flavors of setting up a method that finds an object.
Option A
Object *findObject(Key &key);
Return null when an object can't be found. Nice and simple. I'd go with this one. The alternative approaches below are for people who don't hate out-params.
Option B
void findObject(Key &key, Object &found);
Pass in a reference to variable that will be receiving the object. The method thrown an exception when an object can't be found. This convention is probably more suitable if it's not really expected for an object not to be found -- hence you throw an exception to signify that it's an unexpected case.
Option C
bool findObject(Key &key, Object &found);
The method returns false when an object can't be found. The advantage of this over option A is that you can check for the error case in one clear step:
if (!findObject(myKey, myObj)) { ...
referring only to the case where null is not considered an exceptional behavior i am definitely for the try method, it is clear, no need to "read the book" or "look before you leap" as was said here
so basically:
bool TryFindObject(RequestParam request, out ResponseParam response)
and this means that the user's code will also be clear
...
if(TryFindObject(request, out response)
{
handleSuccess(response)
}
else
{
handleFailure()
}
...
If it's important for client code to know the difference between found and not found and this is supposed to be a routine behavior, then it's best to return null. Client code can then decide what to do.
Generally it should return null. The code calling the method should decide whether to throw an exception or to attempt something else.
Or return an Option
An option is basically a container class that forces the client to handle booth cases. Scala has this concept, look up it's API.
Then you have methods like T getOrElse(T valueIfNull) on this object thet either return the found object, or an allternative the client specifieces.
Prefer returning null --
If the caller uses it without checking, the exception happens right there anyway.
If the caller doesn't really use it, don't tax him a try/catch block
Unfortunately JDK is inconsistent, if you trying access non existing key in resource bundle, you get not found exception and when you request value from map you get null if it doesn't exists. So I would change winner answer to the following, if found value can be null, then raise exception when it isn't found, otherwise return null. So follow to the rule with one exception, if you need to know why value isn't found then always raise exception, or..
If the method returns a collection, then return an empty collection (like sayed above). But please not Collections.EMPTY_LIST or such! (in case of Java)
If the method retrives a single object, then You have some options.
If the method should always find the result and it's a real exception case not to find the object, then you should throw an exception (in Java: please an unchecked Exception)
(Java only) If you can tolerate that the method throws a checked exception, throw a project specific ObjectNotFoundException or the like. In this case the compiler says you if you forget to handle the exception. (This is my preferred handling of not found things in Java.)
If you say it's really ok, if the object is not found and your Method name is like findBookForAuthorOrReturnNull(..), then you can return null. In this case it is strongly recomminded to use some sort of static check or compiler check, wich prevents dereferencing of the result without a null check. In case of Java it can be eg. FindBugs (see DefaultAnnotation at http://findbugs.sourceforge.net/manual/annotations.html) or IntelliJ-Checking.
Be careful, if you decide to return a null. If you are not the only programmer in project you will get NullPointerExceptions (in Java or whatever in other Languages) at run time! So don't return nulls which are not checked at compile time.
As long as it's supposed to return a reference to the object, returning a NULL should be good.
However, if it's returning the whole bloody thing (like in C++ if you do: 'return blah;' rather than 'return &blah;' (or 'blah' is a pointer), then you can't return a NULL, because it's not of type 'object'. In that case, throwing an exception, or returning a blank object that doesn't have a success flag set is how I would approach the problem.
Don't think anyone mentioned the overhead in exception handling - takes additional resources to load up and process the exception so unless its a true app killing or process stopping event (going forward would cause more harm than good) I would opt for passing back a value the calling environment could interpret as it sees fit.
I agree with what seems to be the consensus here (return null if "not found" is a normal possible outcome, or throw an exception if the semantics of the situation require that the object always be found).
There is, however, a third possibility that might make sense depending on your particular situation. Your method could return a default object of some sort in the "not found" condition, allowing calling code to be assured that it will always receive a valid object without the need for null checking or exception catching.
Return a null, exceptions are exactly that: something your code does that isn't expected.
Exceptions should be exceptional. Return null if it is valid to return a null.
If you are using a library or another class which throws an exception, you should rethrow it. Here is an example. Example2.java is like library and Example.java uses it's object. Main.java is an example to handle this Exception. You should show a meaningful message and (if needed) stack trace to the user in the calling side.
Main.java
public class Main {
public static void main(String[] args) {
Example example = new Example();
try {
Example2 obj = example.doExample();
if(obj == null){
System.out.println("Hey object is null!");
}
} catch (Exception e) {
System.out.println("Congratulations, you caught the exception!");
System.out.println("Here is stack trace:");
e.printStackTrace();
}
}
}
Example.java
/**
* Example.java
* #author Seval
* #date 10/22/2014
*/
public class Example {
/**
* Returns Example2 object
* If there is no Example2 object, throws exception
*
* #return obj Example2
* #throws Exception
*/
public Example2 doExample() throws Exception {
try {
// Get the object
Example2 obj = new Example2();
return obj;
} catch (Exception e) {
// Log the exception and rethrow
// Log.logException(e);
throw e;
}
}
}
Example2.java
/**
* Example2.java
* #author Seval
*
*/
public class Example2 {
/**
* Constructor of Example2
* #throws Exception
*/
public Example2() throws Exception{
throw new Exception("Please set the \"obj\"");
}
}
That really depends on if you expect to find the object, or not. If you follow the school of thought that exceptions should be used for indicating something, well, err, exceptional has occured then:
Object found; return object
Object not-found; throw exception
Otherwise, return null.

Categories

Resources