3

It is possible in Java to throw any Exception even if it is just declared on moment of throwing, example below:

import org.springframework.dao.DataAccessException;

 // DataAccessException - is abstract class

 } catch (DataAccessException dae) {
      throw new DataAccessException("Exception while executing SQL: \n" + sql
            +    "\nparams: " + paramsToString(params), dae) {
                          private static final long serialVersionUID = 1L;
      };
 } 

Please share your ideas how bad or good this approach.

the same question to extending RuntimeException (that is not abstract) and throw it right away.

Roman Ivanov
  • 2,477
  • 3
  • 20
  • 31

2 Answers2

9

Please share your ideas how bad or good this approach.

It should be legal ... according to my understanding of the Java language.

I think it is pointless from a functional perspective. The caller still has to catch the base exception that you created the anonymous subtype of. And it is not like the name of an anonymous subclass conveys any useful information ...

I think it is bad from the perspective of code readability and maintainability. It is obscure for no good reason, and no useful effect that I can discern.

And there is a risk that doing something weird like that it might break things .... such as your debuggers, source-code analysers or some other tool in your Java chain.


In summary, it is a bad idea with no redeeming features.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
0

Yes. Your example is perfectly okay. An Exception instance is just a class (that extends Exception) name plus information that will be needed when it's caught. Often the class name is all you need (for the catch statement). Normally a message and a stack trace are included. (Though they're both rather useless for caught exceptions.) But sometimes more info is needed. Extending a class is one good way to do that.

If performance matters (which when working with SQL it might not) override fillInStackTrace. Filling in the stack trace is slow, and if you're planning to catch the exception, you don't need it.

Don't extend RunTimeException; you won't be warned about methods that could throw it and you may forget to catch it.

RalphChapin
  • 3,108
  • 16
  • 18