【问题标题】:How can I customize the code that is generated when I use "Surround with try/catch"?如何自定义使用“Surround with try/catch”时生成的代码?
【发布时间】:2016-10-01 22:03:44
【问题描述】:

每个 Android 开发者都被以下情况困住了:

public void catchMeThod() {
    throwedMethod();
}

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

由于IOException 是检查异常throwedMethod 迫使我们处理它。

当我将插入符号移到 throwedMethod 中并按 Alt + Enter 时,Android Studio 为我提供了一些可能的场景:

默认情况下,我选择Surround with try/catch 选项,Android Studio 会生成下一个代码:

我的问题是:如何改变这个触发器,替换

e.printStackTrace() 

Log.e(getClass().getSimpleName(), "Handled exception", e);

【问题讨论】:

    标签: android android-studio intellij-idea


    【解决方案1】:

    这些“模板”由 Postfix Completion 管理(Preferences > Editor > General > Postfix Completion > try)。

    遗憾的是,这些是硬编码到 IDE 中的,无法更改。唯一的方法是手动替换它们。

    仅在当前文件中更改

    cmd + R(如果你使用windows/linux则控制)。

    在顶部栏中输入要搜索的文本,在底部栏中输入要替换的文本。然后点击全部替换。

    处处改变

    在项目视图中,右键单击应用程序并选择“在路径中替换”。填写字段并点击“查找”。

    【讨论】:

    • Tim,我想找到一种方法来更改(或添加)触发器。不要到处更换。
    • 蒂姆,我无法更改区块。 AS 说:这个视图是只读的
    • @ssh 我的错。看来这是不可能改变的,它被硬编码到 IDE 中。您将不得不手动替换它们..
    【解决方案2】:
    1. 转到Android Studio Preferences | Editor | File and Code Templates

    2. 选择Code | Catch Statement Body

    3. 替换现有模板:

      ${EXCEPTION}.printStackTrace(); 
      

      与:

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

    预览:

    享受定制的模板:)

    【讨论】:

      猜你喜欢
      • 2022-12-11
      • 1970-01-01
      • 2021-01-21
      • 2012-07-03
      • 2011-01-18
      • 2020-02-19
      • 2013-07-16
      • 2022-11-02
      • 1970-01-01
      相关资源
      最近更新 更多