简体   繁体   English

如何在方法内引发异常?

[英]How to throw an exception within a method?

def max(xs: List[Int]): Int = if(xs.isEmpty) throw java.util.NoSuchElementException else ...

If xs is empty, an exception should be thrown. 如果xs为空,则应引发异常。 However I get an error, since java.util.NoSuchElementException does not match the return type Int 但是我收到一个错误,因为java.util.NoSuchElementException与返回类型Int不匹配

You should try 你应该试试

throw new NoSuchElementException("empty list")

You're trying to throw a class. 您正在尝试上课。 In Scala, just like in Java, you can only throw an instance of a class and not the class itself. 在Scala中,就像在Java中一样,您只能抛出类的实例,而不能抛出类本身。 You'd have to use one of NoSuchElementException's constructors. 您必须使用NoSuchElementException的构造函数之一。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM