Shreyas arya

Generation

generate functionFri, 10 Feb 2023

if a method throws exception then retry 3 attempts

package com.example.retry; import java.io.IOException; public class Retry { public static void main(String[] args) throws IOException { Retry retry = new Retry(); retry.retry(3, () -> retry.dodgyMethod()); } void retry(int attempts, RetryFunction function) throws IOException { while (attempts > 0) { try { function.run(); break; } catch (IOException e) { attempts--; } } } void dodgyMethod() throws IOException { throw new IOException(); } @FunctionalInterface interface RetryFunction { public void run() throws IOException; } }

Questions about programming?Chat with your personal AI assistant