Scala中如何在失败捕获逻辑中打印循环内操作的索引i?
Great question! The problem with your current code is that the Try wraps the entire for loop. When an exception occurs during any iteration, the whole loop terminates, and you have no way to know which index i triggered the failure. To fix this, you need to reduce the scope of Try to each individual loop iteration—here are a couple of clean approaches:
Option 1: Log Failures and Continue Executing
If you want to run all iterations (even after some fail) and log every failed index, wrap each call to doSomething in a Try inside the loop:
import scala.util.{Try, Success, Failure} for (i <- 1 to 1000) { Try(doSomething(df(i))) match { case Success(_) => // Optional: Log success or leave empty if you don't need it case Failure(exception) => println(s"Failure occurred at index $i: ${exception.getMessage}") // Uncomment below to print the full stack trace for debugging: // exception.printStackTrace() } }
This way, a failure in one iteration won't stop the rest, and you get clear visibility into exactly which index caused the error.
Option 2: Stop at the First Failure
If you want to terminate the loop as soon as a failure happens (and capture that index), use foldLeft to track the first failure encountered:
import scala.util.{Try, Success, Failure} val firstFailure = (1 to 1000).foldLeft[Option[(Int, Throwable)]](None) { (failureAccumulator, i) => // Only check the current iteration if we haven't found a failure yet failureAccumulator.orElse { Try(doSomething(df(i))) match { case Failure(exception) => Some((i, exception)) case Success(_) => None } } } firstFailure match { case Some((failedIndex, exception)) => println(s"First failure at index $failedIndex: ${exception.getMessage}") case None => println("All 1000 operations completed successfully!") }
This approach is efficient because it stops processing further iterations once the first failure is found, and it gives you both the problematic index and the full exception details.
内容的提问来源于stack exchange,提问作者user2715182

