Skip to content

Instantly share code, notes, and snippets.

@benjiman
Last active November 2, 2021 18:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benjiman/ed599a1320e80bbf8964926db894fa89 to your computer and use it in GitHub Desktop.
Save benjiman/ed599a1320e80bbf8964926db894fa89 to your computer and use it in GitHub Desktop.
package com.benjiweber.example;
import java.util.Random;
public class ExceptionUnions {
public static void main(String... args) {
try {
foo().check();
} catch (Eint eint) {
System.out.println("eint " + eint.i);
} catch (EString eString) {
System.out.println("estring " + eString.s);
}
Either<Eint,Edouble> x = () -> new Edouble(5.5);
try {
x.check();
} catch (Edouble e) {
System.out.println("double " + e.d);
} catch (Eint e) {
throw new IllegalStateException("Won't be");
}
}
public static Either<Eint, EString> foo() {
// return () -> new Edouble(4.4); // compile failure
return new Random().nextBoolean()
? () -> new Eint(4)
: () -> new EString("blah");
}
interface Either<E1 extends E, E2 extends E> {
void check() throws E1, E2;
}
static class E extends Exception {
public Throwable fillInStackTrace() {
return this;
}
}
static class EString extends E {
String s;
EString(String s) throws EString {
this.s = s;
throw this;
}
}
static class Eint extends E {
int i;
Eint(int i) throws Eint {
this.i = i;
throw this;
}
}
static class Edouble extends E {
double d;
Edouble(double d) throws Edouble {
this.d = d;
throw this;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment