Home > Enterprise >  how to make Intellij extends exception by default not throwable java
how to make Intellij extends exception by default not throwable java

Time:12-05

When I define a new exeption on IntelliJ IDEA Ultimate and use ctlr enter to create the exception class, it extends Throwable by default, I would like to change that to exception but I can't find where it is in the settings.

I've tried to to the settings in Editor -> File and Code Templates but I can't find what I'm searching for.

CodePudding user response:

Overriding default behavior for creating new exception classes in not available yet for IntelliJ IDEA. Here is a feature request.

Still it is possible to use LiveTemplates.

  1. In the main menu, go to File > Settings (or Preferences on macOS).
  2. In the Settings/Preferences dialog, navigate to the Editor > Live Templates section.
  3. In the right pane, find "Java" item and expand it.
  4. Add new entry, e.g. "exc" (or any symbols on your choice).
  5. In the editor window, modify the template code as needed to change the default behavior.

For example, to make the created exception class extend the Exception class instead of Throwable modify the code as follows:

public class $NAME$ extends Exception {
    public $NAME$() {
    }

    public $NAME$(String message) {
        super(message);
    }

    public $NAME$(String message, Throwable cause) {
        super(message, cause);
    }

    public $NAME$(Throwable cause) {
        super(cause);
    }

    protected $NAME$(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

After making the desired changes, click Apply button to save changes.

Usage:

  1. Create a class file
  2. Remove contents except for "package ..." line.
  3. Put cursor somewhere, type exc, push Tab key.
  4. The template will be expanded and the cursor will be at the position where you have to type the name of the exception class.
  • Related