[英]Throw Custom Exception
I'm trying to throw a custom exception.我正在尝试抛出一个自定义异常。
The implementation of the custom exception class is:自定义异常 class 的实现是:
case class customException(smth:String) extends Exception
In my code I wrapped a piece of code that I'm sure throws throw an exception with try/catch to throw my customException.在我的代码中,我包装了一段代码,我确定用 try/catch 抛出异常来抛出我的 customException。
try{
val stateCapitals = Map(
"Alabama" -> "Montgomery",
"Alaska" -> "Juneau",
"Wyoming" -> "Cheyenne")
println("Alabama: " + stateCapitals.get("AlabamaA").get)
}
catch{
case x:Exception=>throw classOf[CustomException]
}
I got a compilation error that says:我得到一个编译错误,上面写着:
found : java.lang.Class[CustomException]
[INFO] required: java.lang.Throwable
[INFO] case x:Exception=>throw classOf[CustomException]
How could I throw my own custom exception on this case?我怎么能在这种情况下抛出我自己的自定义异常? Later I'm checking if the thrown exception is of a type[x] to do something specific.
稍后我将检查抛出的异常是否属于 type[x] 以执行特定操作。
You're not throwing an exception, but the class of an exception (just read the compiler error message...).你不是抛出异常,而是异常的 class (只需阅读编译器错误消息......)。 You have to throw an exception instance.
你必须抛出一个异常实例。
case x:Exception => throw new CustomException("whatever")
It would also be helpful to change your Exception class definition as follows:更改您的异常 class 定义也将有所帮助,如下所示:
case class customException(smth:String) extends Exception(smth)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.