I'm wondering if there is a way in java (pure code, not some Eclipse thing) to "syntactic sugar" up repetitive try catch code. Namely, I have to wrap a bunch of functions
public void foo(){
try{
// bla
} catch (Exception e) {
System.out.println("caught exception:");
e.printStackTrace();
}
}
public void bar(){
try{
// other bla
} catch (Exception e) {
System.out.println("caught exception:");
e.printStackTrace();
}
}
and so on. I'd like to write
@excepted public void foo(){
// bla
}
@excepted public void bar(){
// other bla
}
I think sugar of this type was possible in python. Is it possible in Java?
What are Syntactic Sugars? In computer science, syntactic sugar is syntax within a programming language that is designed to make things easier to read or to express. It makes the language "sweeter" for human use: things can be expressed more clearly, more concisely, or in an alternative style that some may prefer.
It must be used within the method. If an exception occurs at the particular statement in the try block, the rest of the block code will not execute. So, it is recommended not to keep the code in try block that will not throw an exception. Java try block must be followed by either catch or finally block.
Yes, It is possible to have a try block without a catch block by using a final block. As we know, a final block will always execute even there is an exception occurred in a try block, except System.
You can't do something like your pseudocode suggests with annotations, but you can make the method(s) throw:
public void bar() throws Exception {}
And just let it bubble up all the way, catching it wherever you want to, higher up the call tree (or down the call stack, if you prefer).
Wrap up the try/catch in a class/method that accepts an interface. Pass an anonymous implementation to that class/method. Really only good when the exception handling is involved, otherwise similarly noisy.
You could also play AOP/bytecode games, depending on actual use case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With