Android开发之Exception转String的标准姿势

主要分为2种,Javav版本和kotlin版本

咱们先看Java版本,特别简单,以前在外企的时候学到的

public static void main(String[] args) {
        try {
            int a = 1 / 0;
        } catch (Exception e) {
            e.printStackTrace();
            String content = Log.getStackTraceString(e);
        }
    }

就一行代码:Log.getStackTraceString(exception)

咱们再看下Kotlin版本咱们写呢?同样很简单

object demo {
    @JvmStatic
    fun main(args: Array) {
        try {
            val a = 1 / 0
        } catch (e: Exception) {
            e.printStackTrace()
            val content = e.stackTraceToString()
        }
    }
}

说白了核心代码也只有一行:val content = exception.stackTraceToString()

不过Java版本和Kotlin版本底层实现都是一样的,都是写入字符;

Java版本源码

Java版本源码
   public static String getStackTraceString(Throwable tr) {
        if (tr == null) {
            return "";
        }

        // This is to reduce the amount of log spew that apps do in the non-error
        // condition of the network being unavailable.
        Throwable t = tr;
        while (t != null) {
            if (t instanceof UnknownHostException) {
                return "";
            }
            t = t.getCause();
        }

        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        tr.printStackTrace(pw);
        pw.flush();
        return sw.toString();
    }

咱们再看下Kotlin版本源码

Kotlin源码

@SinceKotlin("1.4")
public actual fun Throwable.stackTraceToString(): String {
    val sw = StringWriter()
    val pw = PrintWriter(sw)
    printStackTrace(pw)
    pw.flush()
    return sw.toString()
}

你可能感兴趣的:(Android技巧,异常转字符串,异常转String,exception转字符串,exception转Str,Android异常转字符串)