2

Possible Duplicate:
What can you throw in Java?

Why can't I take an Exception in a reference of Object. I mean consider the following code:

try{.......}
catch(Object ex){.......}

It shows an error, where as we knows that it's possible for all the objects of any class to be referenced by Object.

Community
  • 1
  • 1
Ankur Verma
  • 79
  • 2
  • 10

5 Answers5

4

The Java Language specification says that only Throwables can be thrown.

http://java.sun.com/docs/books/jls/third_edition/html/exceptions.html#44043

Every exception is represented by an instance of the class Throwable or one of its subclasses; such an object can be used to carry information from the point at which an exception occurs to the handler that catches it.

The language could have been defined differently, but Java tends to define a base type for any kind of thing that is intended to be used in a particular way and defines methods in that base class to support common patterns. Throwable in particular supports chaining and stack trace printing. It would not be possible to chain exceptions as easily if the only thing you knew about an exception was that it was a reference type.

Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
1

You can assign a reference of an Exception to an Object without a problem. But Objects can't be thrown or catched.

That only works for Throwables.

Jens Schauder
  • 77,657
  • 34
  • 181
  • 348
1

So that in catch block you can be sure to get some details on exception like getCause(), getMessage(), getStackTrace(). If its generic Object, you wont have access to these methods without explicit casting, and you wont be still sure that these method actually exist. As its instance of Throwable, you are sure that you can retrieve these details from exception (the object in the catch).

kdabir
  • 9,623
  • 3
  • 43
  • 45
0

You can't because only subclasses of Throwable can be thrown. I suppose it would be possible for them to have allowed you to use Object in a catch block, instead -- the only superclass of Throwable -- but what would be the point, since the variable would always refer to a Throwable instance.

Ernest Friedman-Hill
  • 80,601
  • 10
  • 150
  • 186
0

Maybe you are coming from C++ where anything can be thrown, even an int. Java exceptions extend Throwable. Object does not extend it (of course).

Ernest Friedman-Hill
  • 80,601
  • 10
  • 150
  • 186
Andrew Lazarus
  • 18,205
  • 3
  • 35
  • 53