Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

try-catch syntactic sugar in java

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?

like image 885
andyInCambridge Avatar asked Jan 10 '12 19:01

andyInCambridge


People also ask

What is syntactic sugar 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.

Can we use try catch in class?

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.

Does try always need catch?

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.


2 Answers

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).

like image 60
sarumont Avatar answered Nov 11 '22 13:11

sarumont


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.

like image 2
Dave Newton Avatar answered Nov 11 '22 15:11

Dave Newton