File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Why so many Exception Handling classes ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Why so many Exception Handling classes ?" Watch "Why so many Exception Handling classes ?" New topic
Author

Why so many Exception Handling classes ?

arun mahajan
Ranch Hand

Joined: Dec 07, 2001
Posts: 305
Hello Everybody,
If I write the following program in two ways:

The only differance I know in this that in first style i am catching all exception through super class though in later I am writing all exception formats and than writing super exception as otherwise all other exception under it will have no meaning.
But my question what is a better way and why?
regards,
Arun
Bosun Bello
Ranch Hand

Joined: Nov 06, 2000
Posts: 1510
The second format is better. because if there is a chance you will throw IOException, you will get a more meaningful message. Bottom line...catching specific exceptions makes the code clearer and easy to maintain.


Bosun (SCJP, SCWCD)
So much trouble in the world -- Bob Marley
Valentin Crettaz
Gold Digger
Sheriff

Joined: Aug 26, 2001
Posts: 7610
Usually if you care about exception and error handling you shouldn't just catch Exception (or Throwable for that matter) and pop up a generic error mesage to the user. If Java provides such a great flexibility in exception and error handling, you should take advantage of it. Imagine you have a network application that accesses a back-end database. There are several things that may fail, among others, the network can fail (IOException) or the database access may fail too (SQLException). If you just catch Exception, the user is never going to know what didn't work. That's just an example, but in order to be very informative to the user or to yourself as a developer you should really give exception handling a big importance and benefit from it.
If certain parts of your code do not require an extensive error handling then just catching Exception is fine. But if you need to be sure of what went wrong then break your catch blocks down into the most specific to least specific exceptions, give good information messages and figure out a good way out.


SCJP 5, SCJD, SCBCD, SCWCD, SCDJWS, IBM XML
[Blog] [Blogroll] [My Reviews] My Linked In
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
Val makes an excellent point. The idea behind catching individual exceptions is so that you know exactly what happened and can deal with it accordingly. Similary, when you write a method that is capable of throwing exceptions, it's generally better to define the individual exceptions it can throw, rather than simply saying that it throws exception. Take the following example:

When you're the only one going to be using your code, then perhaps you "know" enough to know what exceptions might really be thrown by a method. However, if you're writing a method that may be used by other people, you don't want to force them to dig through your code in order to determine what exceptions can really be thrown. Take a look through the Java API and you'll see examples of this everywhere. I'm yet to find a method in the API that declares that it throws Exception.
I hope that helps,
Corey


SCJP Tipline, etc.
amit taneja
Ranch Hand

Joined: Mar 14, 2003
Posts: 810
I have made the following program

------------------------
package test;

class A {

public void method(){

int i=2,j=0;
try{
System.out.println(" hii before error");
int k=1/j;
System.out.println(" hii after error");
}

catch(Exception e){
System.out.println(e);
System.out.println("in Exception");
}
}

public static void main(String args[]){
A a= new A();
a.method();
}
}



which prints o/p as


C:\>java test/A
hii before error
java.lang.ArithmeticException: / by zero
in Exception


==========================================

and when i run the pgramm with specific exception
like

package test;

class A {

public void method(){

int i=2,j=0;
try{
System.out.println(" hii before error");
int k=1/j;
System.out.println(" hii after error");
}

catch(ArithmeticException e){
System.out.println(e.getMessage());
System.out.println("in ArithmeticException");
}
catch(Exception e){
System.out.println(e);
System.out.println("in Exception");
}
}

public static void main(String args[]){
A a= new A();
a.method();
}
}

i get following exception....


C:\>java test/A
hii before error
/ by zero
in ArithmeticException


So I didn't understand what is the benifit of using specific exception
other then
better code practice
customising error message for each exception.

so, Exception can also show atleast what kind of individual exception occured !!

please clarify more

thanks


Thanks and Regards, Amit Taneja
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38851
    
  23
Benifit of using specific exception other then better code practice
You need both. You need specific exception handling and you need better code practice. This is a bad way to handle division by zero:-Two problems:
  • 1: You have two potential exit points from the method
  • 2: You are missing a potentially simpler method
  • but not you are returning 0 when passing 0; An alternative would be:-But I don't know how to make ArithmeticException a checked exception; this last technique forces the calling method to deal with the exception. None of these three techniques is ideal.

    The reason for using multiple exception handling is that different exceptions require different treatment. It is one thing to have a message asking the user to re-enter data which are in the wrong format (eg entering 123.45 as an entry when an int was called for); it is another when there are several possible responses, some of whihc will have to be handled by the app itself, and some which will require help from support staff.
    So when you are reading from a file, IOException, FileNotFoundException and EOFException (or is it EndOfFileException) all call for different responses.

    Similarly when trying to get a URL, a SocketException (which means you can't connect to the Internet) requires different handling from a MalformedURLException (which probably only needs a new entry).

    You should be able to work out what sort of Exception is expected from each method by reading its API specification (and whenever you write a method which might throw an Exception, you must name that Exception in its javadoc.) So you can work out from the javadoc which Exceptions to expect, and what sort of message or other response each requires.

    Using is the lazy way out, but it is probably acceptable for testing, where such exceptions as
  • NullPointerException
  • ArrayIndexOutOfBoundsException
  • ClassCastException
  • ArithmeticException (allowing a 0 into your divisions)
  • all probably mean there is a programming error which has to be sorted out.

    Was that of any help??
    CR
    Stan James
    (instanceof Sidekick)
    Ranch Hand

    Joined: Jan 29, 2003
    Posts: 8791
    There are several conflicting forces at work and you have to find the balance that works for the situation every time.

    First: Responding to errors. On one hand, it's sometimes good to know exactly what went wrong in a called method so you can take appropriate action. On the other hand, I'd hate to see a dozen catch clauses all with exactly the same action. When you're catching you can easily decide what granularity is right. When you're throwing you have to guess what the caller might want to know.

    Second: Information hiding. If I use a data repository and it throws SQL exceptions I know that it uses a database and I am forced to import from JDBC just for the exceptions. What if the next release of the repo uses Hibernate and throws Hibernate exceptions? Or RMI and throws RMI exceptions? The repo author should probably write a small number of RepoException classes that give me useful information I can respond to instead of the gory details.

    Third: Logging and error messages. What if I get RepoNotFound exceptions and want to log the gory details? Or if I don't? It would be impossible to write the Repo to satisfy all callers. I like to nest or chain exceptions so the RepoException might capture the stack trace from the root cause exception just so I can print it out ... or not.

    No easy answers, huh.


    A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
     
    I agree. Here's the link: http://aspose.com/file-tools
     
    subject: Why so many Exception Handling classes ?