A more functional try…catch construct in Java
$begingroup$
I saw a question on Stack Overflow asking for a review of a custom try...catch construct that made use of Optional
s, and got the idea to try writing my own version. Mine doesn't use Optional
s though. Each supplied catch
handler is expected to return a value.
I realized about half way through writing this that this is probably an awful idea that should never be used d in the real world for various reasons. I haven't written Java in a few years though, and I'm curious what can be improved.
Example of use:
Integer i =
new Try<>(()-> Integer.parseInt("f"))
.catching(NumberFormatException.class, (e)-> 2)
.catching(IllegalStateException.class, (e) -> 3)
.andFinally(()-> System.out.println("Finally!"));
// Finally!
Integer j =
new Try<>(()-> Integer.parseInt("1"))
.catching(NumberFormatException.class, (e) -> 2)
.execute();
System.out.println(i); // 2
System.out.println(j); // 1
Basically how it works is the Try
object can have catching
methods chained on it that register handlers. When an exception is thrown, it looks for a corresponding handler, and calls it, returning the returned value. If no handler is found, it rethrows the exception.
Major problems:
The need for
.class
is unfortunate. I couldn't think of how else to have the caller indicate the class of exception to be caught though.Non-exception classes can be registered, although it will have no effect other than the minimal memory and CPU usage.
The need for
execute
whenandFinally
isn't used. I can't see how the class would know that allcatch
es have been added though.The need for
new
is unfortunate too. I figured I could take a page from Scala and create a static method that acts as a constructor, but then I'd need to do something likeTry.tryMethod
to reference it, which isn't a whole lot better.
The check in
andFinally
seems like it's unnecessary. Unless someone does something bizarre like:
Try t = new Try<>(() -> null);
t.andFinally(() -> {});
t.andFinally(() -> {});
It shouldn't be possible to add multiple
finally
blocks. I'm not sure to what extent I should stop the user from doing stupid things. I could make the object immutable, but again, I'm not sure if that's necessary.
Since this is basically just exercise code, I'd love to anything at all that could be improved here. This is the first Java I've really written in a few years, so I'm sure there's lots that can be improved.
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Supplier;
public class Try<T> {
private Supplier<T> tryExpr;
private Map<Class, Function<Exception, T>> handlers = new HashMap<>();
private Runnable finallyExpr;
public Try(Supplier<T> tryExpr) {
this.tryExpr = tryExpr;
}
public Try<T> catching(Class ex, Function<Exception, T> handler) {
if(handlers.containsKey(ex)) {
throw new IllegalStateException("exception " + ex.getSimpleName() + " has already been caught");
} else {
handlers.put(ex, handler);
return this;
}
}
public T execute() {
try {
return tryExpr.get();
} catch (Exception e) {
if(handlers.containsKey(e.getClass())) {
Function<Exception, T> handler = handlers.get(e.getClass());
return handler.apply(e);
} else {
throw e;
}
} finally {
if(finallyExpr != null) {
finallyExpr.run();
}
}
}
public T andFinally (Runnable newFinallyExpr) {
if (finallyExpr == null) {
finallyExpr = newFinallyExpr;
} else {
throw new IllegalStateException("Cannot have multiple finally expressions");
}
return execute();
}
}
java error-handling
$endgroup$
add a comment |
$begingroup$
I saw a question on Stack Overflow asking for a review of a custom try...catch construct that made use of Optional
s, and got the idea to try writing my own version. Mine doesn't use Optional
s though. Each supplied catch
handler is expected to return a value.
I realized about half way through writing this that this is probably an awful idea that should never be used d in the real world for various reasons. I haven't written Java in a few years though, and I'm curious what can be improved.
Example of use:
Integer i =
new Try<>(()-> Integer.parseInt("f"))
.catching(NumberFormatException.class, (e)-> 2)
.catching(IllegalStateException.class, (e) -> 3)
.andFinally(()-> System.out.println("Finally!"));
// Finally!
Integer j =
new Try<>(()-> Integer.parseInt("1"))
.catching(NumberFormatException.class, (e) -> 2)
.execute();
System.out.println(i); // 2
System.out.println(j); // 1
Basically how it works is the Try
object can have catching
methods chained on it that register handlers. When an exception is thrown, it looks for a corresponding handler, and calls it, returning the returned value. If no handler is found, it rethrows the exception.
Major problems:
The need for
.class
is unfortunate. I couldn't think of how else to have the caller indicate the class of exception to be caught though.Non-exception classes can be registered, although it will have no effect other than the minimal memory and CPU usage.
The need for
execute
whenandFinally
isn't used. I can't see how the class would know that allcatch
es have been added though.The need for
new
is unfortunate too. I figured I could take a page from Scala and create a static method that acts as a constructor, but then I'd need to do something likeTry.tryMethod
to reference it, which isn't a whole lot better.
The check in
andFinally
seems like it's unnecessary. Unless someone does something bizarre like:
Try t = new Try<>(() -> null);
t.andFinally(() -> {});
t.andFinally(() -> {});
It shouldn't be possible to add multiple
finally
blocks. I'm not sure to what extent I should stop the user from doing stupid things. I could make the object immutable, but again, I'm not sure if that's necessary.
Since this is basically just exercise code, I'd love to anything at all that could be improved here. This is the first Java I've really written in a few years, so I'm sure there's lots that can be improved.
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Supplier;
public class Try<T> {
private Supplier<T> tryExpr;
private Map<Class, Function<Exception, T>> handlers = new HashMap<>();
private Runnable finallyExpr;
public Try(Supplier<T> tryExpr) {
this.tryExpr = tryExpr;
}
public Try<T> catching(Class ex, Function<Exception, T> handler) {
if(handlers.containsKey(ex)) {
throw new IllegalStateException("exception " + ex.getSimpleName() + " has already been caught");
} else {
handlers.put(ex, handler);
return this;
}
}
public T execute() {
try {
return tryExpr.get();
} catch (Exception e) {
if(handlers.containsKey(e.getClass())) {
Function<Exception, T> handler = handlers.get(e.getClass());
return handler.apply(e);
} else {
throw e;
}
} finally {
if(finallyExpr != null) {
finallyExpr.run();
}
}
}
public T andFinally (Runnable newFinallyExpr) {
if (finallyExpr == null) {
finallyExpr = newFinallyExpr;
} else {
throw new IllegalStateException("Cannot have multiple finally expressions");
}
return execute();
}
}
java error-handling
$endgroup$
add a comment |
$begingroup$
I saw a question on Stack Overflow asking for a review of a custom try...catch construct that made use of Optional
s, and got the idea to try writing my own version. Mine doesn't use Optional
s though. Each supplied catch
handler is expected to return a value.
I realized about half way through writing this that this is probably an awful idea that should never be used d in the real world for various reasons. I haven't written Java in a few years though, and I'm curious what can be improved.
Example of use:
Integer i =
new Try<>(()-> Integer.parseInt("f"))
.catching(NumberFormatException.class, (e)-> 2)
.catching(IllegalStateException.class, (e) -> 3)
.andFinally(()-> System.out.println("Finally!"));
// Finally!
Integer j =
new Try<>(()-> Integer.parseInt("1"))
.catching(NumberFormatException.class, (e) -> 2)
.execute();
System.out.println(i); // 2
System.out.println(j); // 1
Basically how it works is the Try
object can have catching
methods chained on it that register handlers. When an exception is thrown, it looks for a corresponding handler, and calls it, returning the returned value. If no handler is found, it rethrows the exception.
Major problems:
The need for
.class
is unfortunate. I couldn't think of how else to have the caller indicate the class of exception to be caught though.Non-exception classes can be registered, although it will have no effect other than the minimal memory and CPU usage.
The need for
execute
whenandFinally
isn't used. I can't see how the class would know that allcatch
es have been added though.The need for
new
is unfortunate too. I figured I could take a page from Scala and create a static method that acts as a constructor, but then I'd need to do something likeTry.tryMethod
to reference it, which isn't a whole lot better.
The check in
andFinally
seems like it's unnecessary. Unless someone does something bizarre like:
Try t = new Try<>(() -> null);
t.andFinally(() -> {});
t.andFinally(() -> {});
It shouldn't be possible to add multiple
finally
blocks. I'm not sure to what extent I should stop the user from doing stupid things. I could make the object immutable, but again, I'm not sure if that's necessary.
Since this is basically just exercise code, I'd love to anything at all that could be improved here. This is the first Java I've really written in a few years, so I'm sure there's lots that can be improved.
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Supplier;
public class Try<T> {
private Supplier<T> tryExpr;
private Map<Class, Function<Exception, T>> handlers = new HashMap<>();
private Runnable finallyExpr;
public Try(Supplier<T> tryExpr) {
this.tryExpr = tryExpr;
}
public Try<T> catching(Class ex, Function<Exception, T> handler) {
if(handlers.containsKey(ex)) {
throw new IllegalStateException("exception " + ex.getSimpleName() + " has already been caught");
} else {
handlers.put(ex, handler);
return this;
}
}
public T execute() {
try {
return tryExpr.get();
} catch (Exception e) {
if(handlers.containsKey(e.getClass())) {
Function<Exception, T> handler = handlers.get(e.getClass());
return handler.apply(e);
} else {
throw e;
}
} finally {
if(finallyExpr != null) {
finallyExpr.run();
}
}
}
public T andFinally (Runnable newFinallyExpr) {
if (finallyExpr == null) {
finallyExpr = newFinallyExpr;
} else {
throw new IllegalStateException("Cannot have multiple finally expressions");
}
return execute();
}
}
java error-handling
$endgroup$
I saw a question on Stack Overflow asking for a review of a custom try...catch construct that made use of Optional
s, and got the idea to try writing my own version. Mine doesn't use Optional
s though. Each supplied catch
handler is expected to return a value.
I realized about half way through writing this that this is probably an awful idea that should never be used d in the real world for various reasons. I haven't written Java in a few years though, and I'm curious what can be improved.
Example of use:
Integer i =
new Try<>(()-> Integer.parseInt("f"))
.catching(NumberFormatException.class, (e)-> 2)
.catching(IllegalStateException.class, (e) -> 3)
.andFinally(()-> System.out.println("Finally!"));
// Finally!
Integer j =
new Try<>(()-> Integer.parseInt("1"))
.catching(NumberFormatException.class, (e) -> 2)
.execute();
System.out.println(i); // 2
System.out.println(j); // 1
Basically how it works is the Try
object can have catching
methods chained on it that register handlers. When an exception is thrown, it looks for a corresponding handler, and calls it, returning the returned value. If no handler is found, it rethrows the exception.
Major problems:
The need for
.class
is unfortunate. I couldn't think of how else to have the caller indicate the class of exception to be caught though.Non-exception classes can be registered, although it will have no effect other than the minimal memory and CPU usage.
The need for
execute
whenandFinally
isn't used. I can't see how the class would know that allcatch
es have been added though.The need for
new
is unfortunate too. I figured I could take a page from Scala and create a static method that acts as a constructor, but then I'd need to do something likeTry.tryMethod
to reference it, which isn't a whole lot better.
The check in
andFinally
seems like it's unnecessary. Unless someone does something bizarre like:
Try t = new Try<>(() -> null);
t.andFinally(() -> {});
t.andFinally(() -> {});
It shouldn't be possible to add multiple
finally
blocks. I'm not sure to what extent I should stop the user from doing stupid things. I could make the object immutable, but again, I'm not sure if that's necessary.
Since this is basically just exercise code, I'd love to anything at all that could be improved here. This is the first Java I've really written in a few years, so I'm sure there's lots that can be improved.
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Supplier;
public class Try<T> {
private Supplier<T> tryExpr;
private Map<Class, Function<Exception, T>> handlers = new HashMap<>();
private Runnable finallyExpr;
public Try(Supplier<T> tryExpr) {
this.tryExpr = tryExpr;
}
public Try<T> catching(Class ex, Function<Exception, T> handler) {
if(handlers.containsKey(ex)) {
throw new IllegalStateException("exception " + ex.getSimpleName() + " has already been caught");
} else {
handlers.put(ex, handler);
return this;
}
}
public T execute() {
try {
return tryExpr.get();
} catch (Exception e) {
if(handlers.containsKey(e.getClass())) {
Function<Exception, T> handler = handlers.get(e.getClass());
return handler.apply(e);
} else {
throw e;
}
} finally {
if(finallyExpr != null) {
finallyExpr.run();
}
}
}
public T andFinally (Runnable newFinallyExpr) {
if (finallyExpr == null) {
finallyExpr = newFinallyExpr;
} else {
throw new IllegalStateException("Cannot have multiple finally expressions");
}
return execute();
}
}
java error-handling
java error-handling
edited 3 mins ago
Carcigenicate
asked 8 mins ago
CarcigenicateCarcigenicate
3,46211631
3,46211631
add a comment |
add a comment |
0
active
oldest
votes
Your Answer
StackExchange.ifUsing("editor", function () {
return StackExchange.using("mathjaxEditing", function () {
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
});
});
}, "mathjax-editing");
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "196"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f214147%2fa-more-functional-try-catch-construct-in-java%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
0
active
oldest
votes
0
active
oldest
votes
active
oldest
votes
active
oldest
votes
Thanks for contributing an answer to Code Review Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f214147%2fa-more-functional-try-catch-construct-in-java%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown