我怎样才能在增强的for循环捕获异常并重新启动进程这个循环? [英] How can I catch an exception in an enhanced for loop and restart the process for this loop?

查看:155
本文介绍了我怎样才能在增强的for循环捕获异常并重新启动进程这个循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开始增强,由于它的循环工作的最佳实践,并与habilities 的ArrayList 工作

I have started working with enhanced for loops due to it's best practices and habilities to work with ArrayLists.

我的code基本上得到包含链接到歌曲和解析这个列表下载歌曲的ArrayList。一个抛出的异常是TimeoutException异常,加入WTO要求当服务器超载或有一个与互联网连接的不稳定通常发生。

My code basically gets an ArrayList that contains links to songs and parses this list downloading the songs. One of the exceptions thrown is the TimeoutException, whitch normally happens when the server is overloaded or there's an instability with the internet connection.

要澄清:

try
{
    for(Track track : album.getTracks())
    {
        songdown.downloadTrack(track, directorio, formataudio);
    }
}
catch (TimeoutException te)
{ 
    System.out.println("Timeout!");
}

轨道是一个ArrayList加入WTO要求由一个由songdown.downloadTrack功能解析之一。如果下载失败,一个TimeoutException引发的,但我不知道如何才能删除我已经生成的文件并重新启动的语句从同一轨道,从而使下载可能再次发生治疗这种例外。

track is an ArrayList whitch is parsed one by one by the songdown.downloadTrack function. When a download fails, a TimeoutException is raised, but I don't know how to treat this exception in order to delete the file I have generated and restart the for statement from the same track, so that the download can happen again.

推荐答案

虽然这是一个悬而未决的问题是如何明智,这将是,你会用一个内循环,直到重试成功的更好。事情是这样的:

While it's an open question how advisable this would be, you'd be better off with an inner loop that retries until successful. Something like this:

for (Track track : album.getTracks()) {
    boolean downloaded = false;
    while (!downloaded) {
        try {
            songdown.downloadTrack(track, directorio, formataudio);
            downloaded = true;
        } catch (TimeoutException te) { /* delete partially downloaded song etc */ }
    }
}

您可能会想重试的循环或其他一些额外的检查,每次迭代中的最大#避免无限循环。

You'd likely want a max # of retries within each iteration of the for loop or some other additional checks to avoid infinite looping.

这篇关于我怎样才能在增强的for循环捕获异常并重新启动进程这个循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆