Search code examples
javaexceptionunchecked

java force developer to handle unchecked exception


Is there a way to developer user to handle all unchecked exception in the code so that code would not compile until all unchecked exception are handled? I would like to force user to handle exceptions like

iterator.next()

Solution

  • No you cant. Usually if you want to force the user to handle unchecked exception you manually catch them and wrap them in checked exceptions

    eg

    Integer a;
    try {
        a = 1;
    }
    catch (NullPointerException e) {
         throw new Exception(e);
    }
    

    and a is null the NPE will be thrown. It is then wrapped in a checked Exception. (Exception is probably too generic here so you may have to create your own checked excpetion class)

    The trouble with this pattern is that you have to check everywhere for where there may be unchecked exceptions. These are not declared as part of the method signatures so it may mean trawling through the API.

    Or you could be even dirtier and have lots of try/catch blocks which catch Exception. Exception is a superclass of RuntimeException so it would catch unchecked exceptions.

    I am not sure what you want to do is the right approach. Unchecked exceptions are usually programmer errors so are really meant to be caught. They are usually bugs in code. (and there is a massive debate about the point of unchecked/checked exception which you can google)