Pregunta

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()
¿Fue útil?

Solución

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)

Otros consejos

No, you can't exactly force user to handle unchekced exceptions that is not what unchecked exceptions are meant for. For force handling there are checked exceptions. However, You can ask user to handle all the exceptions in your program.

No, you can't. AFAIK the best chance you is to use a shutdown hook

No, you cannot force the user to do that, you could ask him very nicely though ...

No.

And how would the compiler even do that? Since these exceptions are unchecked, they are not declared in the method signatures (for the most part), so how would it know what needs to be handled?

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top