How can I catch the exception in the extended loop and restart the process for this loop?

I started working with improved loops because of his best practices and robes for working with ArrayLists .

My code basically gets an ArrayList that contains links to songs and parses this list loading songs. One of the exceptions thrown is a TimeoutException, which usually occurs when the server is overloaded or there is instability with the Internet connection.

To clarify:

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

track is an ArrayList that is parsed one by one by the songdown.downloadTrack function. When the download fails, a TimeoutException is thrown, but I donโ€™t know how to handle this exception to delete the file that I generated and restart the for statement from the same track so that the download can repeat.

+1
source share
4 answers

While the open question is, how appropriate is it, you will be better off with an inner loop that retries until it succeeds. Something like that:

 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 will probably need the maximum number of repetitions in each iteration of the for loop or some other additional checks to avoid an infinite loop.

+6
source

Please check this out first. First of all, the catch block should begin after the try block completes.

You can catch the exception in the catch block and write the code that you want to execute when the exception occurs, which in your case starts again and deletes half of the downloaded songs.

0
source

There are, of course, many valid approaches.

Here is one possibility:

 int failureCount = 0; while (failureCount < maxFailures) { try { parseAndDownload(someList); break; } catch (Exception ex) { failureCount ++; } } 
0
source

Here is an example fragment, I think you can solve your problem by following this path

 ArrayList<String> a = new ArrayList<String>(); a.add("a"); a.add("w"); a.add("d"); //Iterator<String> i = a.iterator(); for(String s:a){ try{ if(s.equals("w")){ throw new Exception("Hello"); }else{ System.out.println(s); } }catch (Exception e) { continue; } } 

In this snippet, I explicitly selected the exception, when it is launched, the catch block will be executed, there I used the continue keyword. This keyword is intended to solve this situation.

0
source

Source: https://habr.com/ru/post/911258/


All Articles