You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Kotlin中为自定义异常追加消息且不改变异常类型

问题描述

我已创建如下自定义异常,运行正常:

open class MyException(message: String): Exception(message)

class MyException1(message: String): MyException(message)
class MyException2(message: String): MyException(message)
class MyException3(message: String): MyException(message)

fun process1() {
    throw MyException1("from process1")
}

fun process2() {
    try {
        process1()
    } catch(e: Exception) {
        if ( e is MyException ) throw e
    }
}

fun main() {
    process2()
}

当前输出

Exception in thread "main" MyException1: from process1
 at FileKt.process1 (File.kt:8) 
 at FileKt.process2 (File.kt:13) 
 at FileKt.main (File.kt:22) 

我希望在process2函数中为错误消息添加“process-2”相关内容,且不改变异常类型。预期实现的输出如下:

Exception in thread "main" MyException1: from process2 | from process1
 at FileKt.process1 (File.kt:8) 
 at FileKt.process2 (File.kt:13) 
 at FileKt.main (File.kt:22) 

我不想为异常使用data class

解决方案

由于Java原生Exception的消息字段是不可变的,我们可以在自定义基类MyException中维护一个可变的消息属性,并重写message getter返回这个可变字段,同时添加消息追加方法。这样无需创建新异常实例,就能在保留原类型和栈轨迹的前提下修改消息内容。

修改后的完整代码:

open class MyException(private var customMessage: String) : Exception(customMessage) {
    // 重写message属性,返回我们维护的可变消息
    override val message: String
        get() = customMessage

    // 添加前缀消息的方法
    fun prependMessage(prefix: String) {
        customMessage = "$prefix | $customMessage"
    }
}

class MyException1(message: String): MyException(message)
class MyException2(message: String): MyException(message)
class MyException3(message: String): MyException(message)

fun process1() {
    throw MyException1("from process1")
}

fun process2() {
    try {
        process1()
    } catch(e: Exception) {
        if (e is MyException) {
            e.prependMessage("from process2")
            throw e
        }
    }
}

fun main() {
    process2()
}

运行这段代码后,输出将与预期完全一致:

Exception in thread "main" MyException1: from process2 | from process1
 at FileKt.process1 (File.kt:12) 
 at FileKt.process2 (File.kt:20) 
 at FileKt.main (File.kt:28) 

内容的提问来源于stack exchange,提问作者Metropol_Tilkisi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 09:02:34