2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

e.printStackTrace() と android.util.Log をつなぐ

Posted at
IDE-default
try {
  ...
} catch (Exception e) {
  e.printStackTrace();
}

例外送出するコードを開発環境にお任せで保護させると、こんな感じのガード文が出てくる。

しかし Android には標準出力や標準エラー出力がないため、この printStackTrace はどこへとも知れず、電子の闇に葬り去られる。

以下のようにすると Logcat で例外の内容を見られるようになるので、デバッグが捗る(かもしれない)。

with-Logcat
try {
  ...
} catch (Exception e) {
  e.printStackTrace(new PrintWriter(new Writer() {
    private final StringBuffer buffer = new StringBuffer();

    @Override
    public void write(char[] cs, int offset, int length) {
      buffer.append(cs, offset, length);
    }

    @Override
    public void flush() {
      Log.e("Exception", buffer.toString());
      buffer.setLength(0);
    }

    @Override
    public void close() {
    }
  }, true));
}

StringBuffer を経由せず write で直接 Logcat に転送するのでもいい。 Error で出力するのか Information とするか、はたまた Debug か。それからタグをどうするか。お好みで調整してください)

2
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?