You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Scala中如何在失败捕获逻辑中打印循环内操作的索引i?

How to Capture the Loop Index on Failure in Scala

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:36:18