Hacker News new | ask | show | jobs
by p2t2p 1747 days ago
> I wish that programming languages supported some contract-like mechanism of declaring: "This method can throw only X, Y and Z". If the method throws anything else, a system-defined "UnexpectedException" would be thrown, encapsulating the invalid one

Boy, do I have some news for you... Like about 25 years old news. Did you ever try java?

1 comments

Yes. What I'm thinking of are _not_ checked exceptions, at least not at compile-time.
Can you elaborate then?
I did in the original post, and that's why I used C++ as example instead of Java. A method declares `throws X, Y, Z` and _runtime_ checks that no other exception escapes. No source changes needed if you add W to the list. And if some other exception escapes, it's wrapped in `UnexpectedException` that is reserved for and throwable only by the runtime.
I guess we could extend Project Lombok to do this. You'll still have your "throws" statement but then the tool would wrap calls to catch those that are not listed in "throws" statement and wrap them as you say.
That'd be cool.

It just occurred to me that I could probably do the same with attributes and DynamicProxy for C#. And also implement additional checks like "IF X is thrown, its properties must satisfiy some constraints.". (I program both in Java and C# these days.)

Such "UnexpectedException" as I suggested would serve two purposes: 1) well, knowing that something unexpected happened and allowing you to handle it with "last chance handler", 2) helping the developers maintain the contract. If you change a method so that it can throw some new exceptions (compared to the previous version), you've broken its contract/compatibility. This would then show up during testing.

> You'll still have your "throws" statement but then the tool would wrap calls t

Yes. Fortunately, Java allows you to mention subclasses of RuntimeException in "throws" declaration.

But... both purposes 1) and 2) are already served perfectly fine with the current exception models already: you catch Exception at the very top-level in the "last chance handler", and if during testing an unexpected exception is thrown, it bubbles up past the existing handlers right into this "last chance handler". What does re-wrapping help with, exactly?