I have a question about throwing exceptions in Java, a kind of misunderstanding from my side, as it seems, which I would like to clarify for myself.
I have been reading that the two basic ways of handling exception code are:
1.) throwing an exception in a try-block with "throw new ...", and catching it immediately in a catch-block - the so called try-throw-catch mechanism.
2.) throwing an exception in a method with "throw new ..." and then declaring in the header of the method that this method might throw an exception with "throws ..." - the so called pass-the-buck.
I have recently read that "it doesn't make any sense to throw an exception and then catch it in the same method", which made me think whether I understand the thing in the wrong way, or the person who had written this had something else in mind. Doesn't the first way of handling exceptions does exactly this (the try-throw-catch mechanism) ? I mean, it throws an exception and catches it in the same method. I have read that it is a better practice to throw an exception in one method, and catch it in another method, but this is just one (probably better) way. The other way is also legal and correct, isn't it?
Would you, please, give me a comment on this ? Thank you very much.
Exceptions should be thrown from a method when that method is incapable of resolving the exception on its own.
For example, a FileNotFoundException is thrown from new FileInputStream(new File(filename)) because the FileInputStream itself can't handle a case where a file is missing; that exception needs to get thrown so the end-user application can handle the problem.
There are some cases where exceptions could be handled within a method. For example, a Document model method throwing a BadLocationException could be handled within a sufficiently intelligent method. Depending on the problem, either the exception can be handled or re-thrown.
(Anyway, I'd argue that throwing an exception from within a try-catch block so the catch block can be executed represents really bad logic flow)
I think you misunderstood the first case. Normally you add a try-catch-block when you call some method which may throw exceptions. Catching locally thrown exceptions indeed doesn't make much sense. In particular you shouldn't use exceptions to exit from loops, as this is extremely slow compared to a standard approach.
Doesn't the first way of handling
exceptions does exactly this (the
try-throw-catch mechanism)? I mean, it
throws an exception and catches it in
the same method.
That's not a "way of handling exceptions" - it's utter nonsense. The whole point of exceptions is to let another method up the call stack handle it. If you're going to handle the condition within the same method, there's no point in using an exception - that's what if() is for! If that makes the control flow of your method too complicated, you should probably refactor some of the logic into separate methods - and then it might make sense to have those throw exception that the remaining method body catches.
That being said, I can imagine one special case where it could make sense to throw and catch an exception in the same method: when you're already calling a method that may throw an exception and have a catch block to handle it, then in some cases it could make sense to throw an exception to indicate a similar problem that the existing catch block can handle in the same way.
The person who wrote "it doesn't make any sense to throw an exception and then catch it in the same method" is entitled to their opinion, but it's not widely shared. There are plenty of cases where throwing and catching an exception in the same method is what's needed. The simplest is where you are doing a sequence of operations and the failure of any one of them makes the rest invalid. If you detect that one of these operations fails it's perfectly reasonable to throw an exception and catch it at the end of the method. In fact it's the logical way of doing things. Arguably you could rewrite the code to not use the exception, maybe with some status flags and a break statement or two, but why would you? Using an exception makes it clear what's going on and improves code readability.
I'm gonna answer your questions in turn, then add some comments to the end. I'm not an authority on exception handling, but I hope my comments are helpful.
"Doesn't the first way of handling exceptions does exactly this"?
My answer is yes, as you describe it the first method does operate by throwing and catching an exception in the same method. However, I don't know that try-throw-catch has to work as you describe it.
"I have read that it is a better practice to throw an exception in one method, and catch it in another method, but this is just one (probably better) way. The other way is also legal and correct, isn't it?"
I agree that catching exceptions from a second method is better, but the first way is legal. Is it correct? well that's for you to decide, it is your code, after all.
For the most part, I agree that it doesn't make sense to throw an exception then immediately catch that exception in the same method. If we do this because the method is particularly long/complex and handling the error using other logic would complicate things more, then I would suggest moving some of this logic to another method and calling that method and catching its exception.
If our code is simpler, then it may be easy to handle the error using code that doesn't consist of throwing an exception.
My comments:
The try-throw-catch mechanism you mentioned may not need the exception to be thrown in the same method. I would have to read the text you found to be certain, but I would expect that it isn't necessary. If it didn't need the exception to be thrown in the same method, then your exceptions handling strategy is a combination of 1) and 2).
In the combo, one method would use try-throw-catch mechanism to catch an exception thrown by a called method. It seems to me that 1) and 2) should work together to form your exception handling strategy.
Now, maybe someone will come along and give us some wonderful reasons why we might want to throw an exception in the same method. I expect there are some, but to me they seem the exceptions, not the rule.
Cheers,
Ed
With the first way do you mean something like this:
try {
ok = doSomething();
if (!ok) {
throw new Exception("Error");
}
ok = doSomethingElse();
}catch (Exception e) {
}
This will allow you to exit the try-catch block without executing the rest of it. This is the only valid usage I can think of throwing an exception with throw and catching it yourself in a try-catch block. However, standard if blocks should be used instead. I don't understand why someone should throw an exception and then catch it himself.
The second way is more standard, especially if the caller of the method that throws an exception is an external module. This is a way of signaling that something real wrong happened. It is the responsibility of the caller to handle the exception.
If you're going to manually throw an exception, then obviously you know there has been some error that needs to be handled. Rather than throw the new exception, then catch it, then immediately handle the error, why not just handle the error? You (and the processor) don't need to go through all the work of generating an exception and catching it. The exception also makes the code harder to read and debug.
You would throw an exception, rather than just handling the error immediately, if:
Other code, like the code that called your method, should handle the error. For example, if your code is not UI code, then it probably shouldn't generate windows. This is your method #2.
You can take advantage of the try, catch, finally block. It's possible that you could write cleaner code this way, but I think that 90% of the time your code would be more readable using simple if statements.
My expierence is that using the first method gets your code quickly unreadable - since the functionality and the error-handling is getting mixed up. BUT it makes sense in some cases where you have a try{}catch{}finaly{} - for example in file handling or database handling where you ALLWAYS want the connection to be closed.
try{ //do something
}catch(Exception ex){
//log
}finally{
//connection.close
}
For everything else I use the second option - just for the reason to centralize my error-handling routines and keep the readability of the code implementing the businesslogic itself.
In my opinion, try blocks that you write should not include any "throw new" that are caught inside the same method. When you throw an exception, you're saying "I've encountered a situation that I can't handle; somebody else will have to deal with it." Your method with the "throw new" should either create an unchecked exception to throw or declare a checked exception in its method signature.
If you're using 3rd party classes that may throw exceptions, your method should have a try/catch block if you can actually handle the situation if an exception arises. Otherwise, you should defer to another class that can.
I don't create my own exception and then catch it in the same method.
Using an exception for control flow is specifically dealt with in Effective Java, 2nd Edition by Joshua Bloch, Item 57:
Item 57: Use exceptions only for exceptional conditions
...exceptions are, as their name implies, to be used only for exceptional conditions; they should never be used for ordinary control flow. [italics mine]
So while it certainly "works" to use exceptions to control flow, it is not recommended.
The reason why that would seem as nonsense ( throwing and catching in the same method ) is because that would be an scenario of using exceptions for flow control. If you already have enough data as to identify the condition where the exception should be thrown then you could use that information to use a condition instead.
See below:
1) Throwing and catching exception in same method ( wrong )
public void method() {
try {
workA...
workA...
workA...
workA...
if( conditionIvalid() && notEnoughWhatever() && isWrongMoment() ) {
throw new IllegalStateException("No the rigth time" );
}
workB...
workB...
workB...
workB...
} catch( IllegalStateException iee ) {
System.out.println( "Skiped workB...");
}
workC....
workC....
workC....
workC....
}
In this scenario the exception throwing are used to skip the section "workB".
This would be better done like this:
2) Using condition to control flow ( right )
public void method() {
workA...
workA...
workA...
workA...
if( !(conditionIvalid() && notEnoughWhatever() && isWrongMoment() ) ) {
//throw new IllegalStateException("No the rigth time" );
workB...
workB...
workB...
workB...
}
workC....
workC....
workC....
workC....
}
And then you can refactor the condition:
if( !(conditionIvalid() && notEnoughWhatever() && isWrongMoment() ) ) {
for
if( canProceedWithWorkB() ) {
implemented as:
boolean canProceedWithWorkB() {
return !(conditionIvalid() && notEnoughWhatever() && isWrongMoment() );
}
Related
Could you please tell me which approach is better in below two code blocks?
catch (MyException e) {
throw new MyException ("Error processing request", e);
}
Or
catch (MyException e) {
throw e;
}
In order to compare two approaches, they should do the same thing. These two do not do the same thing.
The first approach would be better because you would change its message to a more user friendly one. Perhaps you could also log it (stacktrace or whatever...) before rethrowing it.
The second approach is better regarding performance. Actually, it would be even better if you did not catch the exception at all and let it throw it self.
You have to choose what is preferable, based on user experience and perhaps logging or performance. By default (and not always) I would choose the first.
Hope I helped!
I do not see point in catching the exception and throwing it again. Once rare scenario could be that you need to perform some operation when the exception has occurred but at the same time report the exception to the caller to take appropriate action.
If this is the case then, first approach is better because you are just throwing the same exception again (instead of creating a new once). Btw, both the approaches will preserve the stack trace, just the case is that first one will avoid creation of unnecessary object.
Eg:
catch (MyException e) {
// May be perform some clean-up activity and throw
throw new MyException ("Error processing request", e);
}
Preserve the inner exception, and I don't have an issue. Although, I don't think it makes sense to catch and then rethrow like that. Surely it would be better to just throw a custom-made exception?
What ever the case you can keep StackTrace, there is no issue. But it should be meanning full,there is no point catch and throw same Exception.
You can wrap the original exception like in your first option if you want to include any additional useful information for calling methods.
The first one, because the second approach (rethrow the same exception without any processing) is useless.
Typically you need to define exception processing at start of project. Will you use checked or unchecked exceptions? Will you use standard or your custom exceptions? How will you use exception inheritance? Where will you process (log) exceptions? What are information to pass in exceptions. Once you answear such questions, then it is time to start building your API.
This is more of best practice question.
I'm working with old Java code at the moment. I'm seeing a lot of subclasses of Exception only overwrite the constructors. I'm not sure if there is any practical use of subclassing Exception like this. I think just calling the Exception constructor and pass in a message would be just as effective, and there wouldn't be many subclasses around. Code is liability.
The point of subclassing is that your code can distinguish different types of failure and treat them differently. If you just change the message, then a human can distinguish them in the logs, but that's all.
If the exceptions you are seeing are not actually handled differently, but just caught in a catch-all catch(Exception e) then perhaps someone was being over-enthusiastic with the subclasses, but it is often useful for cleanly separating layers of code and working out which classes should handle which kinds of problem.
For example, one type of exception may indicate a timeout, and it may be appropriate to retry after a short delay, whereas another type of exception indicates an unrecoverable failure (an invalid query, perhaps) which must be thrown up to a higher level or perhaps indicated to the user.
To add to the other answers:
If you extend Exception and throw it, you're declaring a new checked exception. It will have to be declared on the throws clause of your method. You are saying to the caller: "Here is a unusual case which you must code for".
I think checked exceptions are over-used. They are only really useful in situations where the caller can expect to recover from the problem. The vast majority of exceptions I have seen are the kind that the caller cannot reasonably expect to recover from. In this case you should use a RuntimeException descendant such as IllegalStateException or IllegalArgumentException and let top-level error handling take care of it.
This is done to allow more cleaner and more precise catching of exceptions. If all of your code just throws Exception, your exception-handling code will have to look like this:
try {
// ...
throw new Exception("configuration error");
// ...
throw new Exception("missing value error");
// etc.
} catch (Exception e) {
// do something
}
And it will be awkward at the least to handle different kinds of errors in different ways. More importantly, this code will swallow all exceptions, even ones you weren't expecting and for which you haven't written specific error-handling logic. On the other hand, if you write
try {
// ...
throw new ConfigurationException();
// ...
throw new MissingValueException();
// etc.
} catch (ConfigurationException e) {
System.err.println("error: bad configuration");
System.exit(1);
} catch (MissingValueException e) {
return DEFAULT_VALUE;
}
you'll be able to easily and cleanly handle different kinds of errors, and won't have to worry that your error handling code will be run in situations that you didn't expect it to.
When you have a subclass, you can catch it. You can't catch an exception selectively depending on its message.
Subclasses are more descriptive and easier to use:
throw new Exception("User does not exist " + userName);
compared to:
throw new UserNotExistsException(userName);
also the latter exception can have getUserName() method and field accordingly to extract important information when caught. You don't want to parse exception message, don't you?
Subclassing is the way to go. later in the lifetime of the application you may have to change the exception message. Who knows it may be displayed on a page and the wording needs to be adjusted.
Wrapping the error message in its own Exception subclass helps maintain a clean code and easily test against a given error category.
This is on Java 6
Can I have a common method to handle my exceptions - so instead of doing this n times in each method
try {
// Do something
} catch (XException e) {
// Do something
} catch (YException e) {
// Do something
} catch (ZException e) {
// Do something
}
I have
try {
// Do something
} catch (Exception e) {
handleAll (e);
}
and method handleAll(e) does
if e.instanceOf(XException)
else if e.instanceOf(YException)
else if e.instanceOf(ZException)
Is there anything wrong with the 2nd approach?
Update:
My original question was about "centralizing the handling" in one place for both checked and runtime exceptions. The answers have pointed out I should avoid instanceof().
#aioobe's idea looks very neat to me. Are there any negative opinions on that approach?
There is one minor problem as I see it. Since you really want the handleAll method to rethrow any uncaught exception, it has to be declared throws Exception. This means that so does the methods that call handleAll.
If X-, Y- and ZException are all RuntimeExceptions I see nothing wrong with this. (I may have overlooked something though, as this is the first time I've seen this approach.)
To be sure that the instanceof approach behaves exactly as the catch clauses would, I would consider designing the handleAll(RuntimeException e) like this though:
private void handleAll(RuntimeException e) {
try {
throw e;
} catch (XException xe) {
...
} catch (YException xe) {
...
} catch (ZException xe) {
...
}
}
It's a BAD approach. It will reduce LOC (Line Of Code) but it will create difficult to understand, More resource dependent (It requires more memory and processing capacity). it also reduce Readability.
So first one is the best one
You can do this, but I don't think it's good coding style. It's convenient to keep exception handlers close to the lines that throw the Exceptions.
Suppose your code changes, and throws a new Exception. Then you have to update the method that handles them; so now you have to make changes in two places. Same happens if a particular Exception is no longer thrown by the code, or if you decide that some Exceptions should be handled at a higher level.
Also, I'm wary of "catch (Exception exc)". It's too general, try to make your Exception handlers as specific as possible.
Java 7 will make things better. Because catching multiple exceptions is possible.
There is something really wrong with the second approach: if the called method signature is modified and throws a new kind of exception, the code will still compile fine, whereas you have not handled this new exception correctly.
Using the first approach, the compiler will produce an error, which will force you to handle the new exception.
The second approach will catch all Exceptions, including RunTimeExceptions. Make sure you handle them correctly.
I think every exception is unique (when compararized place in code, not the time when exception is thrown) so you should not generilaze exception handling.
You might want to handle exception little difference each time IE. if some where is thrown FileNotFoundException you might create a new file but other time that might be fatal Exception that causes applications termination.
If a destructor throws in C++ during stack unwinding caused by an exception, the program terminates. (That's why destructors should never throw in C++.) Example:
struct Foo
{
~Foo()
{
throw 2; // whoops, already throwing 1 at this point, let's terminate!
}
};
int main()
{
Foo foo;
throw 1;
}
terminate called after throwing an instance of 'int'
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
If a finally block is entered in Java because of an exception in the corresponding try block and that finally block throws a second exception, the first exception is silently swallowed. Example:
public static void foo() throws Exception
{
try
{
throw new Exception("first");
}
finally
{
throw new Exception("second");
}
}
public static void main(String[] args)
{
try
{
foo();
}
catch (Exception e)
{
System.out.println(e.getMessage()); // prints "second"
}
}
This question crossed my mind: Could a programming language handle multiple exceptions being thrown at the same time? Would that be useful? Have you ever missed that ability? Is there a language that already supports this? Is there any experience with such an approach?
Any thoughts?
Think in terms of flow control. Exceptions are fundamentally just fancy setjmp/longjmp or setcc/callcc anyway. The exception object is used to select a particular place to jump to, like an address. The exception handler simply recurses on the current exception, longjmping until it is handled.
Handling two exceptions at a time is simply a matter of bundling them together into one, such that the result produces coherent flow control. I can think of two alternatives:
Combine them into an uncatchable exception. It would amount to unwinding the entire stack and ignoring all handlers. This creates the risk of an exception cascade causing totally random behavior.
Somehow construct their Cartesian product. Yeah, right.
The C++ methodology serves the interest of predictability well.
You can chain exceptions. http://java.sun.com/docs/books/tutorial/essential/exceptions/chained.html
try {
} catch (IOException e) {
throw new SampleException("Other IOException", e);
}
You can also have a try catch inside your finnally too.
try{
}catch(Exception e){
}finally{
try{
throw new SampleException("foo");
}catch(Exception e){
}
}
Edit:
Also you can have multiple catches.
I don't think multiple exceptions would be a good idea, because an exception is already something you need to recover from. The only reason to have more than one exception I can think of is if you use it as part of your logic (like multiple returns), wich would be deviating from the original purpose of the idea of the Exception.
Besides, how can you produce two exceptions at the same time?
Could a programming language handle multiple exceptions? Sure, I don't see why not. Would this be useful? No, I would say it would not be. Error handling and resumption is very hard as it is - I don't see how adding combinatorial explosion to the problem would help things.
Yes, it is possible for a language to support throwing multiple exceptions at a time; however, that also means that programmers need to handle multiple exceptions at a time as well, so there is definitely a tradeoff. I have heard of languages that have this although I am having trouble coming up with the list off the top of my head; I believe LINQ or PLINQ may be one of those languages, but I don't quite remember. Anyway, there are different ways that multiple exceptions can be thrown... one way is to use exception chaining, either by forcing one exception to become the "cause" or "previouslyProgatingException" of the other, or to bottle all of the exceptions up into a single exception representing the fact that multiple exceptions have been thrown. I suppose a language could also introduce a catch clause that lets you specify multiple exception types at once, although that would be a poor design choice, IMHO, as the number of handlers is large enough as is, and that would result in an explosion of catch clauses just to handle every single possible combination.
C++ std::exception_ptr allows you store exceptions. So it should be possible to embed exceptions in other exceptions and give you the impression that you have the stack on thrown exceptions. This could be useful if you want to know the root cause of the actual exception.
One situation where multiple thrown exceptions in parallel might be useful, is unit testing with JUnit:
If a test fails, an exception is thrown (either produced by code under test or an assertion).
Each #After method is invoked after the test, whether the test fails or succeeds.
If an After method fails, another exception is thrown.
Only the exception thrown in the After method is displayed in my IDE (Eclipse) for the test result.
I know that JUnit notifies its test listeners about both exceptions, and when debugging a test in Eclipse I can see the first exception appearing in the JUnit view, only to be replaced by the second exception shortly after.
This problem should probably be resolved by making Eclipse remember all notifications for a given test, not only the last one. Having "parallel exceptions", where the exception from the finally does not swallow the one from the try, would solve this issue too.
If you think about it, the situation you've described has Exception("First") as the root cause of Exception("second"), conceptually. The most useful thing for the user would probably be to get a stack dump showing a chain in that order...
In managed platforms, I can think of situations where it might be useful to have a disposer "elevate" an exception to something which is stronger, but not totally fatal to an application. For example, a "command" object's disposer might attempt to unwind the state of its associated connection to cancel any partially-performed commands. If that works, the underlying code may attempt to do other things with the connection. If the attempted "cancel" doesn't work, the exception should probably propagate out to the level where the connection would have been destroyed. In such a case, it may be useful for the exception to contain an "inner exception", though the only way I know to achieve that would be to have the attempted unwinding in a catch block rather than a "finally" block.
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 4 years ago.
Improve this question
I always come across the same problem that when an exception is caught in a function that has a non-void return value I don't know what to return. The following code snippet illustrates my problem.
public Object getObject(){
try{
...
return object;
}
catch(Exception e){
//I have to return something here but what??
return null; // is this a bad design??
}
}
So my questions are:
Is return null bad design?
If so what is seen as a cleaner solution??
thanks.
I would say don't catch the exception if you really can't handle it. And logging isn't considered handling an error. Better to bubble it up to someone who can by throwing the exception.
If you must return a value, and null is the only sensible thing, there's nothing wrong with that. Just document it and make it clear to users what ought to be done. Have a unit test that shows the exception being thrown so developers coming after you can see what the accepted idiom needs to be. It'll also test to make sure that your code throws the exception when it should.
I always come across the same problem that when an exception is caught in a function that has a non-void return value I don't know what to return.
If you don't know what to return, then it means that you don't know how to handle the exception. In that case, re-throw it. Please, don't swallow it silently. And please, don't return null, you don't want to force the caller of the code to write:
Foo foo = bar.getFoo();
if (foo != null) {
// do something with foo
}
This is IMHO a bad design, I personally hate having to write null-checks (many times, null is used where an exception should be thrown instead).
So, as I said, add a throws clause to the method and either totally remote the try/catch block or keep the try/catch if it makes sense (for example if you need to deal with several exceptions) and rethrow the exception as is or wrap it in a custom exception.
Related questions
How to avoid “!= null” statements in Java?
Above all I prefer not to return null. That's something that the user has to explicitly remember to handle as a special case (unless they're expecting a null - is this documented). If they're lucky they'll deference it immediately and suffer an error. If they're unlucky they'll stick it in a collection and suffer the same problem later on.
I think you have two options:
throw an exception. This way the client has to handle it in some fashion (and for this reason I either document it and/or make it checked). Downsides are that exceptions are slow and shouldn't be used for control flow, so I use this for exceptional circumstances (pun intended)
You could make use of the NullObject pattern.
I follow a coding style in which I rarely return a null. If/when I do, that's explicitly documented so clients can cater for it.
Exceptions denote exceptional cases. Assuming your code was supposed to return an object, something must have gone wrong on the way (network error, out of memory, who knows?) and therefore you should not just hush it by returning null.
However, in many cases, you can see in documentation that a method returns a null when such and such condition occurs. The client of that class can then count on this behaviour and handle a null returned, nothing bad about that. See, in this second usage example, it is not an exceptional case - the class is designed to return null under certain conditions - and therefore it's perfectly fine to do so (but do document this intended behaviour).
Thus, at the end of the day, it really depends on whether you can't return the object because of something exceptional in your way, or you simply have no object to return, and it's absolutely fine.
I like the responses that suggest to throw an exception, but that implies that you have designed exception handling into the architecture of your software.
Error handling typically has 3 parts: detection, reporting, and recovery. In my experience, errors fall into classes of severity (the following is an abbreviated list):
Log for debug only
Pause whatever is going on and report to user, waiting for response to continue.
Give up and terminate the program with an apologetic dialogue box.
Your errors should be classified and handling should be as generically and consistently as possible. If you have to consider how to handle each error each time you write some new code, you do not have an effective error handling strategy for your software. I like to have a reporting function which initiates user interaction should continuation be dependent on a user's choice.
The answer as to whether to return a null (a well-worn pattern if I ever saw one) then is dependent on what function logs the error, what can/must the caller do if the function fails and returns the null, and whether or not the severity of the error dictates additional handling.
Exceptions should always be caught by the controller in the end.
Passing a <null> up to the controller makes no sense.
Better to throw/return the original exception up the stack.
It's your code and it's not bad solution. But if you share your code you Shoudn't use it because it can throw unexpected exception (as nullpointer one).
You can of course use
public Object getObject() throws Exception {}
which can give to parent function usable information and will warn that something bad can happen.
Basically I would ditto on Duffymo, with a slight addition:
As he says, if your caller can't handle the exception and recover, then don't catch the exception. Let a higher level function catch it.
If the caller needs to do something but should then appropriately die itself, just rethrow the exception. Like:
SomeObject doStuff()
throws PanicAbortException
{
try
{
int x=functionThatMightThrowException();
... whatever ...
return y;
}
catch (PanicAbortException panic)
{
cleanUpMess();
throw panic; // <-- rethrow the exception
}
}
You might also repackage the exception, like ...
catch (PanicAbortException panic)
{
throw new MoreGenericException("In function xyz: "+panic.getMessage());
}
This is why so much java code is bloated with if (x!=null) {...} clauses. Don't create your own Null Pointer Exceptions.
I would say it is a bad practice. If null is received how do I know if the object is not there or some error happened?
My suggestion is
never ever return NULL if the written type is an array or
Collection. Instead, return an empty Collection or an empty array.
When the return type is an object, it is up to you to return null depending on the scenario. But never ever swallow an exception and return NULL.
Also if you are returning NULL in any scenario, ensure that this is documented in the method.
As Josha Blooch says in the book "Effective Java", the null is a keyword of Java.
This word identifies a memory location without pointer to any other memory location: In my opinion it's better to coding with the separation of behavior about the functional domain (example: you wait for an object of kind A but you receive an object of kind B) and behavior of low-level domain (example: the unavailability of memory).
In your example, I would modify code as :
public Object getObject(){
Object objectReturned=new Object();
try{
/**business logic*/
}
catch(Exception e){
//logging and eventual logic leaving the current ojbect (this) in a consistent state
}
return objectReturned;
}
The disadvantage is to create a complete Object in every call of getObject() (then in situation where the object returned is not read or write).
But I prefer to have same object useless than a NullPointerException because sometimes this exception is very hard to fix.
Some thoughts on how to handle Exceptions
Whether returning null would be good or bad design depends on the Exception and where this snippet is placed in your system.
If the Exception is a NullPointerException you probably apply the catch block somewhat obtrusive (as flow control).
If it is something like IOException and you can't do anything against the reason, you should throw the Exception to the controller.
If the controller is a facade of a component he, translate the Exception to well documented component-specific set of possible Exceptions, that may occur at the interface. And for detailed information you should include the original Exception as nested Exception.