繁体   English   中英

如何访问在Spark Scala的catch块中的try catch块之前声明的变量

[英]How to access variables declared before try catch block in a catch block in spark scala

我在spark-scala代码中定义了以下变量,然后尝试catch块。

var exceptionFlag = ""

try{

  exceptionFlag = "FALSE"

}
catch{
  exceptionFlag = "TRUE"
}

在这个try catch块之后,我需要根据该标志编写逻辑。

if (exceptionFlag = "TRUE"){
   write the error details to hive...
}

我定义的变量无法在catch块中访问,因此无法设置标志。

您能建议如何处理这种情况吗?

谢谢,鲍勃

try ... catch是Scala中的一个表达式,您可以在不使用var的情况下执行相同的操作:

scala> :paste
// Entering paste mode (ctrl-D to finish)

  def test(): Unit ={
    val exceptionFlag = try{
      val x=10/0
      "FALSE"
    }
    catch{
      case ex: Exception=> "TRUE"
    }

    if (exceptionFlag == "TRUE"){
      println("write the error details to hive...")
    }
  }

// Exiting paste mode, now interpreting.

test: ()Unit

scala> test()
write the error details to hive...

scala> 

你可以这样

object Driver{

  def test(): Unit ={
    var exceptionFlag = ""
    try{
      val x=10/0
      exceptionFlag = "FALSE"
    }
    catch{
      case ex: Exception=> exceptionFlag = "TRUE"
    }
    if (exceptionFlag == "TRUE"){
      println("write the error details to hive...")
    }
  }

  def main(arr:Array[String]) {
    test
  }
}

样本输出:

write the error details to hive...

暂无
暂无

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

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