TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

Uniform Handling of Failure in Switch

20 pointsby lichtenbergerover 1 year ago

3 comments

sixthDotover 1 year ago
That reminds me a problem I thought I had in STYX...<p>For a few months I had the feeling that a good switch-expression requires the bottom type... It turns out that the `assert(0)` idiom, used in a lambda, is sufficient:<p><pre><code> var u32 a = switch b do { 1 =&gt; 2, &#x2F;* ... *&#x2F; else =&gt; function(): u32 =&gt; {assert(0, &quot;crash&quot;);}() }; </code></pre> The `else` case (similar to C `default`) simply crashes the program but the type system is happy because the lambda return type is compatible.
评论 #38732019 未加载
DarkNova6over 1 year ago
I think the transformative potential for error handling in Java cannot be overstated. Effectively, this means exceptions can be handled as errors without polluting the return type with an ever-growing list of error-monads.<p>The following example shows this nicely:<p>&gt; Future&lt;String&gt; f = ...<p>&gt; switch (f.get()) {<p>&gt; case String s -&gt; process(s);<p>&gt; case throws ExecutionException(var underlying) -&gt; throw underlying;<p>&gt; case throws TimeoutException e -&gt; cancel();<p>&gt; }<p>Note that I don&#x27;t get the hate for exceptions. Sometimes, handeling the error somewhere up the callstack is exactly the right solution. The problem was that Java did not have convenient syntax for handeling exceptions at call-site.<p>FYI: There was also an interesting discussion in the Java mailing lists also going into some implementation details regarding the representing bytecode:<p><a href="https:&#x2F;&#x2F;mail.openjdk.org&#x2F;pipermail&#x2F;amber-spec-experts&#x2F;2023-December&#x2F;003959.html" rel="nofollow noreferrer">https:&#x2F;&#x2F;mail.openjdk.org&#x2F;pipermail&#x2F;amber-spec-experts&#x2F;2023-D...</a>
评论 #38732854 未加载
throwat2341over 1 year ago
I really think the `case throws` is brilliant.<p>Next, lets add a `never` type to make this legal.<p><pre><code> var foo = switch (bar) { case String s -&gt; s, case Number n -&gt; return, };</code></pre>