In java adjectives ending in -able are interfaces Serializable, Comparable etc... So why is Throwable a class? Wouldn't exception handling be easier if Throwable were an interface? (Edit: e.g. Exception classes don't need to extend Exception/RuntimeException.)
Obviously, changing it now is out the question. But could it be made abstract? Wouldn't that avoid the bad practice of throw new Throwable();
The throwable class implements Serializable Interface and the direct known classes to Throwable are Error and Exception. Throwable contains a snapshot of the execution stack of its thread at the time it was created.
James Gosling: The reason that the Throwable and the rest of those guys are not interfaces is because we decided, or I decided fairly early on. I decided that I wanted to have some state associated with every exception that gets thrown. And you can't do that with interfaces; you can only do that with classes.
Throwable in Java is a class that is the superclass of all exceptions and errors which may occur in Java program. It extends object class. Therefore, throwable class is itself a subclass of the superclass of all Java classes, Object class.
A throwable object is an instance of class Throwable (or one of its subclasses). Exception and Error are two subclasses of class Throwable , and each has many subclasses itself. From now on, we use the term exception for an object that has been thrown.
Here's how James Gosling explained his decision:
Java Developer Connection Program: Why is
Throwablenot an interface? The name kind of suggests it should have been. Being able tocatchfor types, that is, something liketry {} catch (<some interface or class>), instead of only classes. That would make [the] Java [programming language] much more flexible.James Gosling: The reason that the
Throwableand the rest of those guys are not interfaces is because we decided, or I decided fairly early on. I decided that I wanted to have some state associated with every exception that gets thrown. And you can't do that with interfaces; you can only do that with classes. The state that's there is basically standard. There's a message, there's a snapshot, stuff like that — that's always there. and also, if you makeThrowablean interface the temptation is to assign, to make any old object be aThrowablething. It feels stylistically that throwing general objects is probably a bad idea, that the things you want to throw really ought to be things that are intended to be exceptions that really capture the nature of the exception and what went on. They're not just general data structures.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With