Recipe Name:
Exception: Created but not thrown
Description:
Exceptions should be thrown, not just created
Level:
warning
Language:
  • java
Tags:
  • Java basic
  • quality
Documentation

Throwable objects should be thrown at some point in the code. A common mistake is to create a throwable object without throwing it after creation. This would mean that the issue contained in the throwable is lost.

Before:
try {
    String bob = null;
    bob.trim();
} catch (NullPointerException e) {
    new RuntimeException("Found nullpointer", e);
}
After:
try {
    String bob = null;
    bob.trim();
} catch (NullPointerException e) {
    throw new RuntimeException("Found nullpointer", e);
}
Recipe
id: scw:exceptions:not-thrown
version: 10
metadata:
  name: 'Exception: Created but not thrown'
  shortDescription: Exceptions should be thrown, not just created
  level: warning
  language: java
  enabled: true
  comment: ""
  descriptionFile: descriptions/ExceptionCreatedbutnotthrown.html
  tags: Java basic;quality
search:
  instanceCreation:
    not:
      anyOf:
      - in:
          assignment: {}
      - in:
          throw: {}
      - in:
          argument: {}
      - in:
          return: {}
      - in:
          methodcall: {}
      - in:
          expression: {}
    type: java.lang.Throwable
availableFixes:
- name: Add a throw
  actions:
  - rewrite:
      to: throw {{{ . }}}
      target: self