Search code examples
javaioexception

How to only allow a certain number of io exceptions?


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?


Solution

  • 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.