MST
星途 面试题库

面试题:Kotlin自定义异常及多层嵌套异常处理

在Kotlin中,定义一个自定义异常`MyBusinessException`,然后编写一段代码,该代码中有多层函数调用,内层函数可能抛出`MyBusinessException`,外层函数需要捕获并处理这个异常,同时在处理异常时记录异常的堆栈信息到日志文件中,描述一下你将如何设计和实现这个功能。
17.3万 热度难度
编程语言Kotlin

知识考点

AI 面试

面试题答案

一键面试
  1. 定义自定义异常
    class MyBusinessException(message: String) : Exception(message)
    
  2. 内层函数抛出异常
    fun innerFunction() {
        throw MyBusinessException("这是业务异常")
    }
    
  3. 外层函数捕获并处理异常,记录堆栈信息到日志文件
    import java.io.FileWriter
    import java.io.PrintWriter
    
    fun outerFunction() {
        try {
            innerFunction()
        } catch (e: MyBusinessException) {
            val fileWriter = FileWriter("error.log", true)
            val printWriter = PrintWriter(fileWriter)
            e.printStackTrace(printWriter)
            printWriter.close()
            println("捕获到异常并记录到日志文件")
        }
    }
    
  4. 测试代码
    fun main() {
        outerFunction()
    }
    

在上述代码中:

  • 首先定义了MyBusinessException自定义异常类。
  • innerFunction函数模拟内层函数抛出MyBusinessException
  • outerFunction函数通过try - catch块捕获异常,在捕获到异常后,使用FileWriterPrintWriter将异常的堆栈信息写入到error.log日志文件中。
  • main函数用于测试整个流程。