วิธีรับข้อยกเว้นในคอนโซล Scala

ฉันต้องการทำให้วัตถุข้อยกเว้นส่ง val ในคอนโซลที่ฉันสามารถใช้ได้ สิ่งที่ต้องการ:

 try { ... } catch { e => make e a val }

เพื่อที่ฉันจะได้สามารถทำ e.toString หรือสิ่งที่คล้ายกันในคอนโซลได้

ฉันจะทำเช่นนี้ได้อย่างไร?


person SRobertJames    schedule 10.12.2014    source แหล่งที่มา


คำตอบ (4)


คุณสามารถใช้ Try และตรงกับมัน:

Try(...) match {
   case Success(value) => // do something with `value`
   case Failure(e) => // `e` is the `Throwable` that caused the operation to fail
}

หรือหากคุณแค่เล่นวุ่นวายในคอนโซล คุณสามารถบังคับได้:

scala> val e = Try(1/0).failed.get
e: Throwable = java.lang.ArithmeticException: / by zero
person Michael Zajac    schedule 10.12.2014

อย่าเพิ่งจับมัน

$ scala
Welcome to Scala version 2.11.4 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_20).
Type in expressions to have them evaluated.
Type :help for more information.

scala> ???
scala.NotImplementedError: an implementation is missing
  at scala.Predef$.$qmark$qmark$qmark(Predef.scala:225)
  ... 33 elided

scala> lastException
res1: Throwable = scala.NotImplementedError: an implementation is missing

scala> 

นอกจากนี้โดยตรง:

scala> try { ??? } catch { case e: Throwable => $intp.bind("oops", e) }
oops: Throwable = scala.NotImplementedError: an implementation is missing
res2: scala.tools.nsc.interpreter.IR.Result = Success

scala> oops.toString
res3: String = scala.NotImplementedError: an implementation is missing
person som-snytt    schedule 10.12.2014

คุณไม่สามารถลักลอบนำวาล์วออกจากขอบเขตภายในได้ ซึ่งเป็นส่วนสำคัญของบล็อกจับ อย่างไรก็ตาม คุณสามารถใช้ scala.util.Either เพื่อระบุว่าคุณอาจมีค่าส่งคืนอย่างใดอย่างหนึ่งจากสองค่า:

import scala.util._
val answer = try { Right(...) } catch { case e: Throwable => Left(e) }
answer match {
  case Right(r) => // Do something with the successful result r
  case Left(e) => // Do something with the exception e
}
person Rex Kerr    schedule 10.12.2014
comment
ยินดีด้วยที่ครบหกหลักแล้ว คุณจะต้องมีทุ่นลอยสำหรับคะแนนตัวแทนของคุณ - person som-snytt; 10.12.2014
comment
@ som-snytt - ฉันเชื่อว่าคุณจะสังเกตเห็นว่ามีสิ่งแปลก ๆ เริ่มเกิดขึ้นประมาณ 16,777,217 ครั้งหรือไม่ - person Rex Kerr; 10.12.2014

อย่าลืมว่าไม่มีอะไรหยุดคุณจากการส่งคืนข้อยกเว้นจาก catch block เช่นเดียวกับค่าอื่นๆ:

scala> val good = try { 1.hashCode } catch { case e: Throwable => e }
good: Any = 1

scala> val bad = try { null.hashCode } catch { case e: Throwable => e }
bad: Any = java.lang.NullPointerException

อย่างไรก็ตาม คุณจะสูญเสียข้อมูลประเภทเว้นแต่ว่าคุณจะส่งคืนสิ่งที่เป็นประเภทเดียวกันในบล็อก try:

scala> val badOrNull = try { null.hashCode; null } catch { case e: Throwable => e }
badOrNull: Throwable = java.lang.NullPointerException

ในกรณีนี้ คุณจะสูญเสียผลลัพธ์ของ try หากไม่มีข้อยกเว้น

ดูคำตอบอื่นๆ สำหรับโซลูชันประเภทที่ปลอดภัยเพิ่มเติม เช่น Try หรือ Either

person Dan Getz    schedule 10.12.2014