Scala中的自定义异常 [英] Custom Exception in scala

查看:120
本文介绍了Scala中的自定义异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何在Scala中创建扩展 Exception 类的自定义异常,并在异常发生时抛出它们并捕获它们。

how can i create custom exceptions in Scala extending Exception class and throw them when exception occurs as well as catch them.

java中的示例:

class CustomException extends Exception {

  public final static String _FAIL_TO_INSERT = "FAIL_TO_INSERT";

}


推荐答案

final case class CustomException(private val message: String = "", 
                           private val cause: Throwable = None.orNull)
                      extends Exception(message, cause) 

只需尝试捕获:

try {
    throw CustomException("optional")
} catch {
    case c: CustomException =>
          c.printStackTrace
}

这篇关于Scala中的自定义异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆