0

I'm wondering if there is a good and standard way to only allow a certain number of IO exceptions (connection timeout etc.) before you stop trying and maybe send an automated email to let someone know there's a problem. I can think of an ugly way to do it with a try catch block that keeps a counter and checks the value of that counter before the try. Is there a more standard nicer way to implement that?

1 Answers1

0

Just create an ìnt` variable that acts as a counter:

int counter = 0;
while (true){
    try{
        // do something
        break;
    } catch (IOException e) {
        e.printStackTrace();
        counter++;

        if (counter >= 10)
            throw new RuntimeException(e);
    }
}

It will catch the exception, print the stacktrace and only rethrow the exception if the counter exceeds 10. The email sending part will be more difficult for several reasons:

  • You need a library do send emails (AFAIK)
  • You need to configure the email server
  • You need to authenticate against the server (The user either needs to supply a password or you need to hardcode the password --> bad practice)
  • A possible reason for the IOException might be that the machine is not connected to the internet. Sending emails will fail in that case too.
vatbub
  • 2,713
  • 18
  • 41
  • Ok yeah I thought about doing something like this, I just thought there might a different, more (professional?) way (because this is the sorta thing I would wrote in my first java class). I guess the basics do work tho. Thanks! – Marvin Gardens Jul 02 '18 at 14:32
  • If it worked for you, consider marking it as the solution. Thx :-) – vatbub Jul 02 '18 at 14:42
  • If you want to use this code block in many places, I suggest you wrap the counter logic into a separate static method in some common class. – David R Tribble Jul 02 '18 at 14:58
  • I am not a fan of static things where they don't need to be static, but you could make the code more abstract if you'd wrap it in a method and supply a `Runnable` which contains the actual logic – vatbub Jul 02 '18 at 15:04