简体   繁体   中英

How can I customize the code that is generated when I use “Surround with try/catch”?

Each Android developer was stuck with the next situation:

public void catchMeThod() {
    throwedMethod();
}

public void throwedMethod() throws IOException{
    throw new IOException("File is missing.");    
}

Since IOException is Checked exception throwedMethod obliges us to handle it.

When I move the caret inside throwedMethod and press Alt + Enter , Android Studio offers me some possible scenarios:

![在此处输入图像说明

By default I choose the Surround with try/catch option and Android Studio generates the next code:

在此输入图像描述

And my question is: how to change this trigger, to replace

e.printStackTrace() 

with

Log.e(getClass().getSimpleName(), "Handled exception", e);
  1. Goto Android Studio Preferences | Editor | File and Code Templates

  2. Select Code | Catch Statement Body

  3. Replace the existing template from:

     ${EXCEPTION}.printStackTrace(); 

    with:

     Log.e(getClass().getSimpleName(), "Exception handled", ${EXCEPTION}); 

Preview:

自定义try..catch模板

Enjoy the customized template :)

These "templates" are managed by Postfix Completion (Preferences > Editor > General > Postfix Completion > try ).

Sadly, these are hardcoded into the IDE and cannot be changed. The only way is to replace them manually.

Change only in current file

Press cmd + R (or control if you use windows/linux).

In the top bar enter the text to search for, in the bottom bar the text to replace it with. Then click replace all.

在此输入图像描述

Change everywhere

In the project view, right click app and select "replace in path". Fill out the fields and click "find".

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM