LancerX
LancerX

Reputation: 1231

What to return if checked exception occurs?

I wonder what should be returned, when some exception occurs as like in my example

public MyClass createComponent(){
  String className = "foo.MyClass";
  try {
    final Class<? extends MyClass> clazz = Class.forName(className).asSubclass(MyClass.class);
    return clazz.getDeclaredConstructor(List.class, String.class).newInstance(list, name);
  } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) {
    e.printStackTrace();
  }
// return null; //??  
}

Upvotes: 1

Views: 85

Answers (1)

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382132

Depending on the logic of your API and the likeness of the root exception you may

  • return null
  • rethrow the exception
  • let it pass (i.e. declare and don't catch)
  • throw a new exception, embedding the cause

If the exceptions are really exceptional (they should not occur) as seems from your code, you probably should throw a runtime exception or a InternalError stating that there's an internal error in your library. Returning null here would do nothing good and might hide a bug.

Upvotes: 4

Related Questions