Home > java > Retried Operation with generic Exception

Retried Operation with generic Exception

May 20Hits:1
Advertisement

I am looking for a way to get the logic of retrying an operation in a single method while keeping the exception types of the operation.

I.e., the implementation to retry an operation could look like this:

public void retriedOperation(Operable operable, int maxAttempts) throws Exception {     for (int attempt = 0; attempt < maxAttempts; attempt++) {         try {             operable.doOperation();             break;         } catch (Exception e) {             if (attempt + 1 > maxAttempts) {                 throw e;             }         }     } } 

This implementation is however only capable of throwing an unspecified Exception and thereby looses lots of information.

Unfortunately, generic Exceptions can neither be caught nor thrown not be caught in Java, thus something like

public void <ExceptionType extends Exception> retriedOperation(...) throws ExceptionType { ... } 

would only allow to catch an unspecific Exception, check if it is of the right type and then cast it. But if it is of another type, it cannot be thrown with this method header.

Is there a way to implement a generic retry function that preserves specific exceptions?

Answers

Unfortunately, generic Exceptions can neither be caught nor thrown in Java, thus something like ... is not possible.

Change that to:

public void <T extends Exception> retriedOperation(...) throws T { ... }

And it should work just fine. When T is a checked exception, the compiler will complain appropriately. E.g.

obj.<IOException>retriedOperation(...);

Will force the surrounding method to either handle IOException or declare that it throws it. However, as long as Operable specifies that it throws Exception, your code won't work, since the method would have to check if the caught exception is of a particular type it doesn't yet know. The real solution is to change Operable to specify whatever exception it throws:

class Operable<T extends Exception>

And now you can rewrite your method as

public <T extends Exception> void retriedOperation(Operable<T> operable, ...) throws T {
    ...
    } catch (Exception e) {
        if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        } else {
            throw (T) e;
        }
    }
    ...
 }

And everything will work just fine, provided Operable only throws one kind of checked exception. If you need to handle more than one, the solution will get a bit ugly - you'll have to pass a list of class tokens as an argument and check if the caught exception is of a compatible type for any of them. (In retrospect, this wouldn't work as described. You do need class tokens, but you'd need an overload of the method for 2 exceptions, 3 exceptions, etc to get the throws clause right.)

Finally, it seems to me retriedOperation should be a static method.

I'm not a java developer, but this might work for you anyway.

You can try using the instanceof operator.

public void retriedOperation<T>(Operable operable, int maxAttempts) throws Exception {
    for (int attempt = 0; attempt < maxAttempts; attempt++) {
        try {
            operable.doOperation();
            break;
        } catch (Exception e) {
            if (!(e instanceof T) || attempt + 1 > maxAttempts) {
                throw e;
            }
        }
    }
}

Where T is the type of the exception you want to allow.

Related Articles

  • Retried Operation with generic ExceptionMay 20

    I am looking for a way to get the logic of retrying an operation in a single method while keeping the exception types of the operation. I.e., the implementation to retry an operation could look like this: public void retriedOperation(Operable operabl

  • Subversion gets stuck when performing a network based operation after not communicating with the serverFebruary 22

    Our company uses Subversion, and ever since we upgraded to version 1.8 we encounter performance problems in network-based operations such as checkout, update, diff and log. The problem occurs whenever the server is accessed after a long time it wasn'

  • SharePoint 2013 App Update - The operation took too longSeptember 14

    I am baffled by this one. On my dev environment updating my custom app works fine. On my live server I can install the app however when I publish a new version and try to update the app I get error. The operation took too long. Intermittent (Retry op

  • Visual Studio 2010 Web Deploy - slow and full of errorsApril 8

    When I say slow, I'm talking something like 10-30kb per second. And on some files larger than 1MB, I'll occasionally get errors like this: 3/18/2014 12:21:08 PM:C:\Program Files\MSBuild\Microsoft\VisualStudio\v10.0\Web\Microsoft.Web.Publishing.target

  • Provisioning a secondary server using Web Farm Framework 2November 22

    We have 3 new instances (all Windows 2008 R2 Datacenter) running on EC2, one to run as a controller for the web farm, and the other two as web servers (all running IIS 7.5). Installed WFF via Web Platform Installer, we've got the controller provision

  • HttpClient error handlingApril 30

    I would be happy to hear feedback on my implementation of HttpClient. I am not so strong with error handling so I want to improve. My thought process behind this was that IOExceptions can be recoverable and should be tried again. Where as client exce

  • Can a RAID 4 disk setup crash if only 1 hard disk fails? November 26

    I am a web developer. I have not much experience in hardware. For this reason, I use managed servers. This morning, one of the drives in our setup failed. However, the full site went down. I asked my web host what happened and he replied that the har

  • Specific area of the laptop heats up unusually

    Specific area of the laptop heats up unusuallyMarch 2

    This is the image of the laptop that I own [HP Pavilion DV4-2126tx]. Towards the left of the laptop is a RJ-45 socket where I connect the internet cable and close to it is the graphics card, hard drive and the slot for remote control. For the past co

  • Sequential Execution: Orchestrator PatternApril 24

    I built a code piece that makes it easy to execute a set of sequential operations, that might depend on the same parameter value (passed across the execution) or might need a particular parameter. There's also a possibility to manage an error from wi

  • Handling a text field and submit button with AjaxJuly 2

    There's this Ajax-heavy, jQuery-based site which I'm about to work on. There hasn't been much structure in the JavaScript code so far (lots of functions at global scope, hard-coded in the HTML onclick="something(args);". How can I improve upon t

  • Malicious "confirm navigation" dialogs?

    Malicious "confirm navigation" dialogs?August 31

    Some sites, like StackExchange, pop up an "Are you sure you want to leave this page?" dialog when you try to leave under certain conditions, such as if you have a post you haven't finished editing. This is helpful! Unfortunately, malicious or in

  • Extracting exact field value from xml file and creating zip files based on each station type in unix using gzipOctober 30

    I have an xml file as below: <?xml version="1.0" encoding="UTF-8"?> <UnitReport Qunatity="163" start-time="2012-06-22T07:00:01+00:00"> <Station guid="59A7C775-7A2F-4ABD-BD10-B82614D5B846">

  • is there a PAM module for DNSBL lookups?June 28

    I have been enumerating the remaining security concerns on one of my back-end production servers, when I came to the realization that something which could be incredibly useful was missing from my operating systems upstream repository. I have been lo

  • Is there a better way to update NoSQL records in bulk?September 2

    When we started our application we had the choice of going with the traditional MS-SQL normalized database or with a NoSQL database (RavenDB is what we tried out). Here is a simplified version of our schema: <Order OrderNumber="1000" OrderVer

  • Mac node npm can not setup bowerNovember 19

    I try to setup up bower on my Mac Pro. Info: Mac OS X 10.9.5 node v0.10.5 npm 1.2.18 The command i use is: sudo npm install -g bower The install doesn't work and i get the following error: Last login: Tue Nov 18 16:31:37 on ttys001 wutianzhitekiMacBo

  • Factory template method for generalized functorsDecember 25

    (A quick note on terminology: I use 'generalized functor' to refer to a functor that can be initialized from any callable entity, similar to the definition from Alexandrescu's Modern C++ Design. I use 'generic functor' to refer to functors in the gen

  • How to combine Find() and AsNoTracking()?January 23

    How to combine Find() with AsNoTracking() when making queries to an EF context to prevent the returned object from being tracked. This is what I can't do _context.Set<Entity>().AsNoTracking().Find(id); How can I do that? I am using EF version 6. Not

  • Generic RPM that can install on any os - error: RPM is for a different operating systemOctober 6

    How can I make a rpm from a spec file that can be installed on any host? Currently I have a spec file but when installing the rpm on other hosts I get this: package my_software-1.0-1dist is for a different operating system The files in the rpm are ju

  • What does "The IO operation at logical block address # for Disk # was retried." mean when seen in the Windows Server System event log?April 14

    I have multipath IO configured server 2012 blade that shows warnings like the following during MPIO path failure: The IO operation at logical block address 0 for Disk 7 was retried. I know what is causing the warning to happen so I am not looking for

  • Service Design approach - one generic operation, and its implicationsJanuary 3

    The hot topic in our organization is Service Design Approach. First Approach - The team wants to design services which essentially have one operation, can take any XML and return response XML message. The operation and the parameters are in the reque

Copyright (C) 2018 ceus-now.com, All Rights Reserved. webmaster#ceus-now.com 14 q. 0.468 s.