using goto seems natural in here.
A project needs to read pdf file, a pdf file can be one of below.
- Not Protected
- Protected with password1
- Protected with password2
- Protected with password3
A file can only be accessed with correct password, there is no way to know which password the file need upfront. we have to try all cases, (include no password). if none of above password works, throw exception.
PdfReader GetPdfReader(string filePath)
{
PdfReader r = null;
int Retries = 0;
start: try
{
switch (Retries)
{
case 0: r = new PdfReader(filePath); break;
case 1: r = new PdfReader(filePath, password1); break;
case 2: r = new PdfReader(filePath, password2); break;
case 3: r = new PdfReader(filePath, password3); break;
}
}
catch (BadPasswordException ex)
{
if (Retries == 3) throw ex;
Retries++;
goto start;
}
return r;
}
Embed try/catch is working but looks ugly, using goto seem natural.
Two questions:
- Should I replace this goto?
- Is there an elegant way to replace this goto?
Thanks