scala 抛出自定义异常
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6716719/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Throw Custom Exception
提问by Echo
I'm trying to throw a custom exception.
我正在尝试抛出自定义异常。
The implementation of the custom exception class is:
自定义异常类的实现是:
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.
我怎么能在这种情况下抛出我自己的自定义异常?稍后我会检查抛出的异常是否属于类型 [x] 以执行特定操作。
回答by paradigmatic
You're not throwing an exception, but the class of an exception (just read the compiler error message...). You have to throw an exception instance.
您不会抛出异常,而是抛出异常的类(只需阅读编译器错误消息...)。你必须抛出一个异常实例。
case x:Exception => throw new CustomException("whatever")
回答by Vlad
It would also be helpful to change your Exception class definition as follows:
如下更改您的 Exception 类定义也很有帮助:
case class customException(smth:String) extends Exception(smth)

