Related
I want to know the the best programming practice in the following use-case for a method say myMethod--
1) myMethod has some numerical purpose - say modify the contents of an array which is a private variable of the class
2) Before it does so, i need to run some critical checks on the numbers,say check1, check2, check3, any of which if fail, there is no point in going ahead. for eg. check might be to check for any negative numbers in array.
So this brings the question, what should myMethod return, how should the calling function be told that checkX has failed.
You should throw Exceptions if any of these checks fail.
Now the question is what kind of Exception to throw. Checked or unchecked? Checked Exceptions must be caught by the calling code where as unchecked do not (but that means they might bubble up to the top of the call stack all the way up to your main method). There is vigorous debate which is better. Either way, make sure to document which Exceptions are thrown.
In general, you should use checked exceptions for recoverable conditions and unchecked exceptions for programming errors (Effective Java 2nd ed Item 58)
there are many built in unchecked Exceptions in Java that you should use in preference to writing your own including but not limited to.
IllegalArgumentException
IllegalStateException
IndexOutOfBoundsException
NullPointerException
Take a look at the core Java methods to see what they throw.
Exceptions are better than return values because:
You must rely on users to check the return value and do something about it.
You are stuck with a method signature that returns a boolean or return code which might not be what you want.
The Exception can have a very descriptive error message explaining why it was thrown.
You can create a custom checked exception as follows:
class ArrayModificationException extends Exception{
public ArrayModificationException(String message){
super(message);
}
}
now in your "myMethod" add following:
void myMethod() throws ArrayModificationException{
//code to check conditions before modifications
//code to modify an array
if(check fails){
throw new ArrayModificationException("cusom message");
}
}
where custom message would be specific message conveying the exact reason of failure.
Of course the called will decide if to handle it or re-throw it. If this is one of conditions where your code should not try to recover itself you can design this as run-time exception and just throw it without throws clause for your method
There is no "best practice" here. It depends entirely on what your code does, where it's being executed, what the caller of the method expects, what should happen in erroneous cases, etc. Context is key here.
One possibility would be to throw an exception from the failing check, which would then be caught in the calling method.
Another option would to have myMethod return a boolean of true if all of the checks pass and the modification/calculation is done, and false otherwise.
As new_web_programmer said, though, it completely depends on what you are trying to do.
In general after a failed validation I do
throw new IllegalArgumentException("... Clue to the error and its repair...");
IllegalStateException is an alternative here.
This enables the function to continue as desired on success.
If the exception must be catched, not propagated, use your own Exception.
If the check failure is expected to be an exceptional circumstance, then throw an exception. Good examples are if a parameter is null but null is disallowed, or if a array index is out of range.
If your functio is supposed to return a reasonable value based on the inputs, such as returning the Point clisest to 0,0 then you could return a reasonable value based upo the check failures. For example, retur null if the array of Points is empty, or if the array itself is null.
In any case, be sure to clearly document (in the method's javadoc) what inputs result in the failure and what the expected behavior is, so that your callers are not surprised.
This brings up a very old debate whether to use exceptions or error codes.
You can read more about it here:
Exceptions or error codes
try{
check1
}catch(Exception e){
throw new CustomException("failed due to check1");
}
Some thing like this may be a better practice.
So this is regarding an interview question I was recently asked. The interviewer started on this by asking me how we create our custom Exceptions. On answering that, he asked me how I'd create a RunTimeExceptions. I said we'd create them in the same way as we would create the checked Exceptions. Just our custom exception would extend from the RunTimeException class. Then he asked in what scenarios would you create your own RunTimeException. Now I couldn't think of a good answer to that. In none of my projects, we created custom RunTimeExceptions.
I also think that we should never create RunTimeExceptions. JVM can fail only in a finite number of ways and it handles them well. While writing an application we can't predict what runtime exceptions can occur and hence we shouldn't need to handle them. And if we can predict those conditions, they aren't RunTimeExceptions then. Since we neither need new runtime exceptions, nor need a handling of runtimeexceptions, why would we ever need to create a custom RunTimeException. Everything that we can pre-think of as a possible failure condition should be handled at compile time and it would be a checked exception. Right? Only the things that cannot be handled at compile time and the ones that depend on run time things go into the category of RunTimeExceptions.
Even if we write custom RunTimeExceptions and then a custom method that should throw that RunTimeException - how do we make sure that the method will throw that particular RunTimeException. How do we do that mapping. It doesn't seem possible to me.
Am I missing something/ many things here? Kindly advice.
Thanks,
Chan.
I think the interviewer was trying to see if you understand the purpose of runtime exceptions, which is to signal programmer's errors (as opposed to application exceptions, which signal problems with the execution environment).
You can and you should create subclasses of RuntimeException whenever your method needs to signal a condition that amounts to a programming error, and you need to provide additional information regarding the error the exception describes.
For example, consider a class that lets you store data in a sparse multidimensional array. One of the APIs such class would probably provide is a getter that takes an array of indexes. The number of indexes needs to equal the number of dimensions in the array, and each index must be within its bounds. Supplying an array parameter that has an incorrect number of elements, or has one or more element outside its bounds, is a programming error. You need to signal it with a runtime exception. If you want to signal this error, and provide a full account of what went wrong, your subclass IllegalArgumentException, a subclass of RuntimeException, to build your own exception.
Finally, there is one more situation when you want to subclass RuntimeException: when you should provide a "regular" exception, but you do not want your users to wrap each call of your API in a try/catch block. In situations like these, you can replace a single method
void performOperation() throws CustomApplicationException;
with a pair of methods
boolean canPerformOperation();
void performOperation();
The first method tells the caller that it is safe to call the second method in the current state; it never throws an exception.
The second method fail only in the state when the first method returns false, making a failure a programming error, thus justifying the use of RuntimeException to signal such failures.
Checked Exception vs Unchecked Exception is a long time debate among Java developers. I'm not be here to ignite the fire, but only want to share with you how I use it in our work.
For example, another service call my server for customer information. The input is customerID, and I will return a customer object
// Web Service interface
public CustomerInfo getCustomerInformation(int customerId, int securityToken) {
check(securityToken);
Customer customer = merchantService.getCustomer(customerId);
return customer.getInfo();
}
// MerchantService
public Customer getCustomer(int customerId) {
return customerService.getCustomer(customerId);
}
What will happen if the system can't find a particular customer? Of course it will throw an exception or return null. But returning null is bad, since it will make you check null everytime calling from a service. So I go with throwing exception:
// Customer service
public Customer getCustomer(id) {
Customer customer = getCustomerFromDB();
if (customer == null) throw CustomerNotExistedException();
return customer;
}
Now the question is whether CustomerNotExistedException is a Exception or a RuntimeException. If it's a checked exception, you will need to catch and process it at the function that calls getCustomer. That means you must catch it at MerchantService. However, all you want is to produce a 404 error at WebService level, so that catching it at MerchantService won't do anything more than throwing the exception again. It pollutes the code.
In the general case, I often use RuntimeException to let some exception "bubble up" to the level in which they can be processed.
For your reference, I would recommend the book Clean code from Robert C. Martin. It explains quite well how we should use exception to handle errors in Java.
You would create your own RuntimeException subclass if:
You don't want it to be a checked exception, because you don't expect callers to explicitly catch the exception. (Personally I believe that checked exceptions are rather overused in the standard library.)
You still want to provide more information than just a message (just the type itself is a helpful starting point in a log).
HibernateException is an example of this in the Hibernate ORM.
I think when you are creating Custom Exceptions , please don't subclass RuntimeException , it defeats the whole purpose of creating the custom exception.
Even if we write custom RunTimeExceptions and then a custom method that should throw that RunTimeException - how do we make sure that the method will throw that particular RunTimeException.
The point here is actually the caller of the method needn't surround that in a try-catch block as it is not a checked exception. Unless you have a good reason to throw a custom unchecked exception , say , just to provide additional custom information for logging etc. don't do that. Another bad implementation will be sometimes you would to just want to catch the checked exceptions in your code and throw custom unchecked exceptions to get rid of all the try-catch in the caller code.
I have a function which calculates the mean of a list passed as an argument. I would like to know which of Java exception should I throw when I try to compute the mean of a list of size 0.
public double mean (MyLinkedList<? extends Number> list)
{
if (list.isEmpty())
throw new ????????; //If I am not mistaken Java has some defined exception for this case
//code goes here
}
Thanks.
You can throw a new IllegalArgumentException().
Thrown to indicate that a method has been passed an illegal or inappropriate argument.
Just don't forget to pass a clear message as a first argument. This will really help you to understand what happend.
For example "Can't use mean on an empty List".
The question to ask yourself first is whether you should be throwing at all and then, if so, whether it should be a checked or unchecked exception.
Unfortunately, there's no industry best practice on deciding these things, as shown by this StackOverflow answer:
In Java, when should I create a checked exception, and when should it be a runtime exception?
Nevertheless, there are some key considerations:
Your design/vision for how this method is supposed to work (Is it reasonable/normal for the method to be called with 0-size list)?
Consistency with other methods in the class/package
Compliance with your applicable coding standard (if any)
My opinion:
Return Double.NAN or 0 If calling the method with a 0-size list is reasonable/expected/normal, I'd consider returning Double.NAN or 0 if 0 is appropriate for your problem domain.
Throw anIllegalArgumentException If my design says that checking for an empty List is strongly the responsibility of the caller and the documentation for the method is going to clearly state that it is the responsibility of the caller, then I'd use the standard unchecked IllegalArgumentException.
Throw a custom checked exception If the method is part of a statistics package or library where several statistics functions need to deal with an possible empty data set, I'd think this is an exception condition that is part of the problem domain. I'd create a custom (probably checked) exception (e.g. EmptyDataSetException) to be part of the class/package/library and use it across all applicable methods. Making it a checked exceptions helps remind the client to consider how to handle the condition.
You should create a new class that extends Exception and provides details specific to your error. For example you could create a class called EmptyListException that contains the details regarding your error. This could be a very simple exception class that takes no constructor arguments but maybe calls super("Cannot generate mean for an empty list"); to provide a custom message to the stack trace.
A lot of times this isn't done enough...one of my most hated code smells is when developers use a generic exception (even sometimes Exception itself) and pass a string message into the constructor. Doing this is valid but makes the jobs of those implementing your code much harder since they have to catch a generic exception when really only a few things could happen. Exceptions should have the same hierarchy as objects you use for data with each level providing more specific details. The more detailed the exception class, the more detailed and helpful the stack trace is.
I've found this site: Exceptional Strategies to be very useful when creating Exceptions for my applications.
IllegalArgumentException
How about NoSuchElementException. Although IllegalArgumentException might be better.
How about an ArithmeticException - the same as the runtime throws.
Are you currently throwing any other exceptions (or planning to?) Any of the previously mentioned exceptions are fine, or just create your own. The most important thing is propagating the message of what went wrong.
If there's a chance the 'catcher' of the exception might re-throw it, than you may want to investigate any other exceptions the 'catcher' might also throw.
I am not convinced you should be throwing an exception there at all; the average of "nothing" is "nothing" or 0 if you will. If the set is empty, you should simply return 0.
If you really MUST throw an exception, then IllegalStateException or IllegalArgumentException are your best choices.
What is the general rule of thumb when deciding whether to add a throws clause to a method or using a try-catch?
From what I've read myself, the throws should be used when the caller has broken their end of the contract (passed object) and the try-catch should be used when an exception takes place during an operation that is being carried out inside the method. Is this correct? If so, what should be done on the callers side?
P.S: Searched through Google and SO but would like a clear answer on this one.
catch an exception only if you can handle it in a meaningful way
declare throwing the exception upward if it is to be handled by the consumer of the current method
throw exceptions if they are caused by the input parameters (but these are more often unchecked)
In general, a method should throw an exception to its caller when it can't handle the associated problem locally. E.g. if the method is supposed to read from a file with the given path, IOExceptions can't be handled locally in a sensible way. Same applies for invalid input, adding that my personal choice would be to throw an unchecked exception like IllegalArgumentException in this case.
And it should catch an exception from a called method it if:
it is something that can be handled locally (e.g. trying to convert an input string to a number, and if the conversion fails, it is entirely valid to return a default value instead),
or it should not be thrown (e.g. if the exception is coming from an implementation-specific lower layer, whose implementation details should not be visible to the caller — for example I don't want to show that my DAO uses Hibernate for persisting my entities, so I catch all HibernateExceptions locally and convert them into my own exception types).
Here's the way I use it:
Throws:
You just want the code to stop when
an error occurs.
Good with methods that are prone to
errors if certain prerequisites are
not met.
Try-Catch:
When you want to have the program
behave differently with different
errors.
Great if you want to provide
meaningful errors to end users.
I know a lot of people who always use Throws because it's cleaner, but there's just not nearly as much control.
My personnal rule of thumb for that is simple :
Can I handle it in a meaningful way (added from comment)? So put code in try/catch. By handle it, I mean be able to inform the user/recover from error or, in a broader sense, be able to understand how this exception affects the execution of my code.
Elsewhere, throw it away
Note : this replys is now a community wiki, feel free to add more info in.
The decision to add a try-catch or a throws clause to your methods depends on "how you want (or have) to handle your exception".
How to handle an exception is a wide and far from trivial question to answer. It involves specially the decision of where to handle the exception and what actions to implement within the catch block. In fact, how to handle an exception should be a global design decision.
So answering your questions, there is no rule of thumb.
You have to decide where you want to handle your exception and that decision is usually very specific to your domain and application requirements.
If the method where the exception got raised has a sufficent amount of information to deal with it then it should catch, generate useful information about what happened and what data was being processed.
A method should only throws an exception if it can make reasonable guarantees surrounding the state of the object, any parameters passed to the method, and any other objects the method acts upon. For example, a method which is supposed to retrieve from a collection an item which the caller expects to be contained therein might throws a checked exception if the item which was expected to exist in the collection, doesn't. A caller which catches that exception should expect that the collection does not contain the item in question.
Note that while Java will allow checked exceptions to bubble up through a method which is declared as throwing exceptions of the appropriate types, such usage should generally be considered an anti-pattern. Imagine, for example, that some method LookAtSky() is declared as calling FullMoonException, and is expected to throw it when the Moon is full; imagine further, that LookAtSky() calls ExamineJupiter(), which is also declared as throws FullMoonException. If a FullMoonException were thrown by ExamineJupiter(), and if LookAtSky() didn't catch it and either handle it or wrap it in some other exception type, the code which called LookAtSky would assume the exception was a result of Earth's moon being full; it would have no clue that one of Jupiter's moons might be the culprit.
Exceptions which a caller may expect to handle (including essentially all checked exceptions) should only be allowed to percolate up through a method if the exception will mean the same thing to the method's caller as it meant to the called method. If code calls a method which is declared as throwing some checked exception, but the caller isn't expecting it to ever throw that exception in practice (e.g. because it thinks it pre-validated method arguments), the checked exception should be caught and wrapped in some unchecked exception type. If the caller isn't expecting the exception to be thrown, the caller can't be expecting it to have any particular meaning.
When to use what. I searched a lot about this.
There is no hard and fast rule.
"But As a developer, Checked exceptions must be included in a throws clause of the method. This is necessary for the compiler to know which exceptions to check.
By convention, unchecked exceptions should not be included in a throws clause.
Including them is considered to be poor programming practice. The compiler treats them as comments, and does no checking on them."
Source : SCJP 6 book by Kathy Sierra
I ll make it simple for you.
Use throws when you think that the called method is not responsible for the exception (e.g., Invalid parameters from the caller method, item to be searched, fetched not available in the collections or fetch datalist).
Use try catch block(handle the exception in the called method) when you think that your functionality in the called method may result in some exception
If you use a try catch, when the exception occurs, the remaining codes would be still executed.
If you indicate the method to throw the exception, then when the exception occurs, the code would stop being executed right away.
try-catch pair is used when you want to provide customise behaviour, in case if exception occurs.....in other words...you have a solution of your problem (exception occurrence) as per your programme requirements.....
But throws is used when you don't have any specific solution regarding the exception occurrence case...you just don't want to get abnormal termination of your programme....
Hope it is correct :-)
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.