Scala与Java交互的实用技巧
一、Scala方法异常注解
1.1 异常抛出示例
在Java中,我们可以使用 try-catch
块来捕获异常,示例代码如下:
Thrower t = new Thrower();
try {
t.exceptionThrower();
} catch (Exception e) {
System.err.println("Caught the exception.");
e.printStackTrace();
}
在Scala里,如果一个方法可能抛出多个异常,需要为每个异常添加注解。例如:
@throws(classOf[IOException])
@throws(classOf[LineUnavailableException])
@throws(classOf[UnsupportedAudioFileException])
def playSoundFileWithJavaAudio {
// exception throwing code here ...
}
1.2 未添加注解的问题
如果Scala的 exceptionThrower
方法没有使用 @throws
注解,Java开发者在调用该方法时可能不会使用 try-catch
块,也不会声明