Scala-异常

异常

Scala异常语法处理上和Java类似,但是又不尽相同。

Java异常

try {
    int a = 10;
    int b = 0;
    int c = a / b;
} catch (ArithmeticException e){
    // catch时,需要将范围小的写到前面
    e.printStackTrace();
} catch (Exception e){
    e.printStackTrace();
} finally {
    System.out.println("finally");
}

scala异常

Scala中的异常不区分所谓的编译时异常和运行时异常,也无需显示抛出方法异常,所以Scala中没有throws关键字。

try {
    val i = 0
    val j = 10 / i
} catch {
    case e: ArithmeticException => println("算术异常")
    case e: Exception => println("其他异常")
}

如果Java程序调用scala代码,如何明确异常?

增加注解 @throws(Exception)

def main(args: Array[String]): Unit = {

}
@throws[Exception]
def test(): Unit = {
    throw new Exception("abc");
}
posted @ 2022-10-26 14:06  POCOPOCOPOCO  阅读(24)  评论(0编辑  收藏  举报