首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何访问spark scala中catch块中try catch块之前声明的变量

如何访问spark scala中catch块中try catch块之前声明的变量
EN

Stack Overflow用户
提问于 2018-06-06 02:47:00
回答 2查看 321关注 0票数 0

我在spark-scala代码中定义了一个变量,如下所示,并尝试catch块。

var exceptionFlag = ""

try{

  exceptionFlag = "FALSE"

}
catch{
  exceptionFlag = "TRUE"
}

在这个try catch块之后,我需要编写基于标志的逻辑。

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

我定义的变量不能在catch块中访问,所以我不能设置标志。

你能建议一下如何处理这种情况吗?

谢谢,鲍勃

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-06-06 06:11:55

试试..。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> 
票数 1
EN

Stack Overflow用户

发布于 2018-06-06 03:23:45

你可以这样做

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...
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50707020

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档