面试题答案
一键面试- 定义自定义异常:
class MyBusinessException(message: String) : Exception(message)
- 内层函数抛出异常:
fun innerFunction() { throw MyBusinessException("这是业务异常") }
- 外层函数捕获并处理异常,记录堆栈信息到日志文件:
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("捕获到异常并记录到日志文件") } }
- 测试代码:
fun main() { outerFunction() }
在上述代码中:
- 首先定义了
MyBusinessException
自定义异常类。 innerFunction
函数模拟内层函数抛出MyBusinessException
。outerFunction
函数通过try - catch
块捕获异常,在捕获到异常后,使用FileWriter
和PrintWriter
将异常的堆栈信息写入到error.log
日志文件中。main
函数用于测试整个流程。