I have a method in which there is a for loop. The loop looks something similar as below.
DirectoryInfo d = new DirectoryInfo(somePath);
FileInfo[] Files = d.GetFiles();
foreach (FileInfo file in Files)
{
try
{
DoSomething(file.Name);
}
catch (Exception ex)
{
continue;
}
}
What I'm doing is , getting all files from a directory, run the loop all the files, get the file Name and do something. Now what I want is even if DoSomething
method raises an exception, I want the loop to continue and do not break in between. So for that I have written continue
in catch block.
I'm running Sonarqube to check the code quality. It is showing the message "Remove this redundant jump.
" . I want to know how can I remove this Code smell and still achieve what I want.
The continue
statement as the last statement in a loop is redundant. You could do this:
DirectoryInfo d = new DirectoryInfo(somePath);
FileInfo[] Files = d.GetFiles();
foreach (FileInfo file in Files)
{
try
{
DoSomething(file.Name);
}
catch (Exception ex)
{
// do nothing
}
}
This code works exactly the same as yours.