Chaining exceptions
Jesse Phillips
jessekphillips at gmail.com
Wed Nov 18 18:21:42 PST 2009
On Wed, 18 Nov 2009 15:24:11 -0800, Andrei Alexandrescu wrote:
> Consider:
>
> void fun() {
> try {
> throw new Exception("a");
> } finally {
> throw new Exception("b");
> }
> }
>
> Currently this function would unceremoniously terminate the program. I
> think it shouldn't. What should happen is that the "a" exception should
> be propagated unabated, and the "b" exception should be appended to it.
> The Exception class should have a property "next" that returns a
> reference to the next exception thrown (in this case "b"), effectively
> establishing an arbitrarily long singly-linked list of exceptions.
>
> A friend told me that that's what Java does, with the difference that
> the last exception thrown takes over, so the chain comes reversed. I
> strongly believe "a" is the main exception and "b" is a contingent
> exception, so we shouldn't do what Java does. But Java must have some
> good reason to go the other way.
>
> Please chime in with (a) a confirmation/infirmation of Java's mechanism
> above; (b) links to motivations for Java's approach, (c) any comments
> about all of the above.
>
>
> Thanks,
>
> Andrei
Best as I can tell, the Java compiler doesn't do the chaining
automatically. It is up to the one throwing the exception to make the
chain. The exception class just provides a specification that requires
all exceptions to support chaining. This explains why it is not the root
cause that is at the head of the chain.
try {
stmt.executeUpdate(sql);
} catch (SQLException ex) {
throw new
EmployeeLookupException(
"Query failure",ex); // ex is passed to the constructor of the class
}
Example from: http://java.sys-con.com/node/36579
http://www.developer.com/tech/article.php/1431531/Chained-Exceptions-in-
Java.htm
More information about the Digitalmars-d
mailing list