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

Casting caught Exception to Real Type

Christopher McCauley
Greenhorn

Joined: Jan 03, 2005
Posts: 27
Is it possible to catch Exception, cast it the Object Type, lets say ArrayOutOfBoundsException (using getClass() perhaps) and then get the message from that object?

A generic Error / Exception Handler if you will.


JCM<br />good at cookin'
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

You can call getMessage() without casting it to another class; you'll get the appropriate message. If you mean you want to create a message based on the class, then you certainly could use getClass().getName() to get the name of the Exception class.


[Jess in Action][AskingGoodQuestions]
Christopher McCauley
Greenhorn

Joined: Jan 03, 2005
Posts: 27
It seems that everytime I try that, the message returned is '
null' ?.?
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

Unfortunately, some exceptions thrown by the JVM itself traditionally have null messages. This is common for NullPointerExceptions, ArrayIndexOutOfBoundsExceptions, etc.
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
You could always do what one of my long-gone co-workers has done:



Yes, it's true.


Tony Morris
Java Q&A (FAQ, Trivia)
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
Heh - that's pretty horrid. Though I would point out for Christopher's benefit that if you're trying to extract some sort of String description of an exception, toString() is often a better choice than getMessage() - at least for a "general" catch block that catches something like all Exceptions or all RuntimeExceptions. The toString() method usually gives you the exception class name followed by the message (if that message is not null). In many cases the exception name is the error message (or an important part of it), and so you can't assume getMessage() by itself will be sufficient to give you useful information. Unless you've caught a specific type of exception which is known to have reliable messages (e.g. one you wrote yourself, or have tested enough to trust).


"I'm not back." - Bill Harding, Twister
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Casting caught Exception to Real Type