aspose file tools*
The moose likes Beginning Java and the fly likes Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark ""extra" Exception catching ?" Watch ""extra" Exception catching ?" New topic
Author

"extra" Exception catching ?

ben oliver
Ranch Hand

Joined: Mar 28, 2006
Posts: 375
In a try block, I think there should only be a SQLException possibly raised. But, I just like to add another catch block like

catch (Exception e) { e.printStackTrace();
}

to catch in case there is any "Exception" ..

Is this bad habit ? will it have any side effect ? what's your thought ?
Sunny Jain
Ranch Hand

Joined: Jul 23, 2007
Posts: 433

Well I don't think so that is a Bad habit..!!
first try to catch as many exception as you can..!, Later you can catch it by Exception class..!!but you have take care of Exception propagation..!!
I give you one example..
suppose i have one method in one class..!!
method1()
{
try
{
..call to another method..
}
catch(SQLException e)
{
rollback();
}
}

Another method
{
try
{
execute first update --successfully..
execute second update ---> exception..!!
}
catch(NullPointerException npe) {
npe.printStackTrace();
}
catch(Exception e) {

}
}

Now suppose if you have handle Exception in second method..Exception will not propagate to calling method and we will not able to roll back the changes..!!
Please be ensure before you apply Exception..!!


Thanks and Regards,
SCJP 1.5 (90%), SCWCD 1.5 (85%), The Jovial Java, java.util.concurrent tutorial
Mark Newton
Ranch Hand

Joined: Jan 31, 2006
Posts: 129
I would disagree with Sunny Jain and say that you should never catch Exception, for exactly the reason he/she mentioned in the example.

The general rule is that you should only catch exceptions if you know what to do with them. Just catching an exception and doing nothing is usually a bad idea.

Also - Sunny... 115 posts and no [code] tags..?
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39781
    
  28
Not convinced.

Be as specific as possible with Exceptions; avoid sayingas far as possible.

It probably is a bad habit to catch Exception; catch(Exception e) (and even worse "catch(Throwable t)") risks losing the information embodied in the different kinds of Exception, and loses the opportunity to take different actions; you use different kinds of Exception to differentiate the different potential error conditions.

Writing "throw new Exception();" and the associated "throws Exception" force the user to "catch(Exception e)" and again loses the chance to differentiate error types.

And beware of catching unchecked Exceptions; the NPE you quote is probably the worst of all to catch, because most instances of an NPE need to be sorted out by correcting an error in the code. There are only a few unchecked Exceptions, eg NumberFormatException, which are worth catching.

SQLException and ordinary Exception are checked Exceptions; if the methods you are using might throw an SQLException or Exception they must declare it.

[edit]When I said "not convinced" I meant not convinced by Sunny Jain's argument. I agree with David Payne.[/edit]
[ February 02, 2008: Message edited by: Campbell Ritchie ]
Sunny Jain
Ranch Hand

Joined: Jul 23, 2007
Posts: 433

Hi, i think both of them took me wrong..when i wrote the following
catch(Exception e) { }
this doesn't mean that I am not doing anything with exception..!!
and I know its worst to catch Unchecked exception..!! even if i write a code which is catching NPE..My boss is simply gonna to scold me badly..!!
and again his favorite dialog "if you code is throwing NPE..don't call yourself a java programmer.."
I just think about one example on the spot and to illustrate i wrote all this..!!!
some time...we can not predict what could be the exception...!!
so from my point of view it is good to write following:



now suppose while writing some code..i can think about..4 exception..so Whats wrong in catching Exception...!! because if Exception5 happens..there must be someone to catch that..otherwise program will crash..!!
But we should handle the Exception properly..!! sometime we forgot to rollback and some other important activity..!!
so thats why i asked the guy to take care of exception propagation..!
Jeanne Boyarsky
author & internet detective
Marshal

Joined: May 26, 2003
Posts: 30908
    
158

Originally posted by ben oliver:
Is this bad habit ? will it have any side effect ? what's your thought ?

I think it is a bad habit because you just log the exception and continue. While it's possible this is acceptable in your situation, it is likely to be "swallowing the exception." This is where you try to avoid a crash but the program has errors later because it was relying on something that didn't happen.

Suppose the database is unavailable. What should happen? Does it make sense for the program to continue? Can it work without that data? If not, something should happen. This could be printing a message to the user and exiting. But this would normally happen in the main method, not to the method that calls the database. The method that calls the database should just propagate the exeption to the higher level code.

More importantly, suppose there is a null pointer. This is most likely an implementation bug. Catching it and continuing doesn't alert you to the fact that there is an error.


[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39781
    
  28
Originally posted by Sunny Jain:
Hi, i think both of them took me wrong..
Sorry about that, but what you posted is liable to confuse other users. Remember this is the beginners' forum where many of the people posting are very inexperienced and would think what you posted is an example to emulate.
Sunny Jain
Ranch Hand

Joined: Jul 23, 2007
Posts: 433

ok, I understand you all, Next time while posting i will take care in which forum I am posting.
Will try to modify my suggestion in that way
Raghavan Muthu
Ranch Hand

Joined: Apr 20, 2006
Posts: 3355

Originally posted by Sunny Jain:
ok, I understand you all, Next time while posting i will take care in which forum I am posting.
Will try to modify my suggestion in that way


That is really great

As CR said, people whoever posting their queries may definitely take our words for granted! that's where we should not give them wrong guidances if we are not clear. Instead we can clearly say that, "I guess", "I think" so that it may give them a hint.


Everything has got its own deadline including one's EGO!
[CodeBarn] [Java Concepts-easily] [Corey's articles] [SCJP-SUN] [Servlet Examples] [Java Beginners FAQ] [Sun-Java Tutorials] [Java Coding Guidelines]
Raghavan Muthu
Ranch Hand

Joined: Apr 20, 2006
Posts: 3355

Originally posted by ben oliver:
In a try block, I think there should only be a SQLException possibly raised. But, I just like to add another catch block like

catch (Exception e) { e.printStackTrace();
}

to catch in case there is any "Exception" ..

Is this bad habit ? will it have any side effect ? what's your thought ?


Hi ben oliver,

Jeanne Boyarsky has clearly said the effects of dealing with the exceptions.

Adding on top and to your query, what you are dealing is the generic Exception class which is the superclass of all checked exceptions (java.lang.Exception).

As you know a base class object can definitely hold any derived/sub class objects and the catch blocks are executed in a sequential manner, if you have the catch block for the generic Exception type, it will definitely be identified as a match for the specific subclass exception type say, a FileNotFoundException[i], [i]SQLException etc.,

That's why we say that it is a bad practice if you just catch the Exception block in the beginning. So, dealing with the generic Exception is like masking your exception.

As Sunny Jain and Campbell Ritchie told you should first catch the specific exception types so that you will get to know what specific exception had occurred. If not, you will really have a tough time in identifying the kind of exception actually thrown.

That does not mean that you should never handle the generic exception block. You may handle the generic exception as the least of all specific catch blocks once you know for sure that you have handled all types of your expected exceptions and if at all there may be some other unhandled exceptions thrown. In that case, you can perfectly have this in your code block.

Hope this helps!
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39781
    
  28
I still think catch(Exception e) is a bad idea, even though you find it in some books. The only excuse for it is if you have to use a method where some wally has written "throws Exception".

If you have checked Exceptions they must all be declared in a throws statement. If you have undeclared unchecked Exceptions, they might as well propagate, because you are going to have to debug the code anyway.
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
I agree that catching a general Exception (or RuntimeException or even Throwable) is usually a bad idea. But there are a few cases where it makes sense, and not just if some other person has written a "throws Exception" that you have to deal with. Most commonly, if I'm writing a main(String[]) method, or a run() method for a Runnable, then I know that the method I'm writing is at the top of the call stack (or near it), and any exception thrown from this method will simply go to the default handler, which usually just does printStackTrace(). Event handlers are similar. Often I want to log the message with log4j instead. At this level, there is probably nothing else I can do, but I want to at least log the message in the proper place, not let it be handled by the default handler. Exception handling at this level is kind of an emergency backup - typically one hopes that the exception was handled at a lower level, unless the intent was to completely stop the program (or at least the current thread). But if you're coding as part of a team, you don't always have control over what all the other code does, and it can make sense to have an emergency backup plan to ensure good logging, if nothing else.

Also, sometimes it makes perfect sense to declare a method that throws Exception. Look at java.util.concurrent.Callable. This is part of a very general framework for executing arbitrary bits of code, some of which will throw declared exceptions. It's not possible for the authors of the interface to know what those checked exceptions are, in advance. So they just declare that the call() method throws Exception. They have done nothing wrong by doing so - they're just making the best of Java's checked exception policy, which sometimes seems more trouble than it's worth. And because this method throws Exception, anyone implementing an ExcecutorService likewise needs to handle Exception.


"I'm not back." - Bill Harding, Twister
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Jeanne Boyarsky:

I think it is a bad habit because you just log the exception and continue. While it's possible this is acceptable in your situation, it is likely to be "swallowing the exception." This is where you try to avoid a crash but the program has errors later because it was relying on something that didn't happen.


Exactly. I prefer my systems to be fail-fast: http://en.wikipedia.org/wiki/Fail-fast


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Jim Yingst:
Most commonly, if I'm writing a main(String[]) method, or a run() method for a Runnable, then I know that the method I'm writing is at the top of the call stack (or near it), and any exception thrown from this method will simply go to the default handler, which usually just does printStackTrace().


In our projects, we typically simply use a custom ThreadGroup with a more appropriate handler for our threads.

Via the sun.awt.exception.handler system property, you can also register a custom exception handler for the event dispatch thread.

Often I want to log the message with log4j instead. At this level, there is probably nothing else I can do, but I want to at least log the message in the proper place, not let it be handled by the default handler.


Or, in the case of a desktop app, show an error dialog to the user...

Also, sometimes it makes perfect sense to declare a method that throws Exception. Look at java.util.concurrent.Callable. This is part of a very general framework for executing arbitrary bits of code, some of which will throw declared exceptions. It's not possible for the authors of the interface to know what those checked exceptions are, in advance. So they just declare that the call() method throws Exception. They have done nothing wrong by doing so - they're just making the best of Java's checked exception policy, which sometimes seems more trouble than it's worth. And because this method throws Exception, anyone implementing an ExcecutorService likewise needs to handle Exception.


Interestingly, generics could be used here - Callable *could* be declared as

Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
[Ilja]: In our projects, we typically simply use a custom ThreadGroup with a more appropriate handler for our threads.

Yes, that works too, and has the advantage of not requiring people to put those catch blocks in every Runnable/handler/whatever. Still, I think using a "catch Exception" or "catch Throwable" is a valid strategy.

[Ilja]: Via the sun.awt.exception.handler system property, you can also register a custom exception handler for the event dispatch thread.

That sounds a little more risky, just because I'm not aware that there's any firm guarantee that property will be supported in all Java implementations. System.getProperties() has a list of standard properties that are guaranteed to be there, and properties beginning wiht "sun" aren't among them. Still, this may be the best solution currently available.

Here's a relevant RFE from 2002. Yeah, I see they'll get right on that...

[Ilja]: Or, in the case of a desktop app, show an error dialog to the user...

Yup, exactly.

[B][Ilja]: Interestingly, generics could be used here - Callable *could* be declared as

[/B]

Yes, but that only allows one exception type at a time. If your method throws IOException and also InterruptedException, for example, the only possible value of E there is Exception. Anyway, I don't see any problem with call() throwing Exception. The classes that use Callable just need to be able to handle arbitrary exceptions - that's part of their design requirements. I don't see a lot of value in making some ExecutorService implementations that only handle certain types of exceptions. They're much more useful & flexible if they just catch Exception.
[ February 03, 2008: Message edited by: Jim Yingst ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: "extra" Exception catching ?