In fact your Try-catch accepts yes other types of exception, more specific, but you will not escape from having to also treat the more generic type Exception or having to add it to the method declaration.
This occurs for these two reasons:
1) Java has something called checked exceptions
The idea of a checked Exception is to warn the consumer of a method, by signing the method, which exceptions that code can launch, so the consumer needs to explicitly decide what to do with those exceptions.
The consumer options of a method declaring checked exceptions sane:
to) Capture the exception and do something with it:
public void facaAlgo() {
try {
MetodoQueLancaCertaCheckedException();
} catch (CertaCheckedException e) {
// ...faz algo útil com a exceção
}
}
b) Do nothing with the exception and let her propose. In this case, the consumer needs to declare that same exception in his own signature as a checked Exception:
public void facaAlgo() throws CertaCheckedException {
MetodoQueLancaCertaCheckedException();
}
Now the consumer of the method facaSoo also have to either capture the exception or redeclare it in your own signature.
2) The developer of the Fileitem class has been relaxed
This is the second reason you are required to either capture the generic exception Exception or redeclarate it in the signature of your method.
This class belongs to the library apache-Common. Whoever made this class, or precisely this method, decided not to have to decide which exceptions to declare and declared the most generic. All other methods in the class make more specific exceptions.
How you can treat a more specific exception
So have you noticed that this method can trigger more specific exceptions, such as IO, and wants to give a differentiated treatment to this exception. Yes, you can!
Although you don’t escape from having to do something with the Exception, you can do what you need with the most specific exception. If you do not want to declare checked exceptions for the consumer of your code, do so:
public File saveFile(FileItem item, File dirFile, String filename) {
dirFile.mkdirs();
File file = null;
try {
item.write(file);
return file;
} catch (IOException e) {
// ... tratamento específico para estes tipos de exceção
} catch (Exception e) {
throw new RuntimeException(e);
}
}
Or, whether or not you want to have Exception as a checked Exception of your method, do so:
public File saveFile(FileItem item, File dirFile, String filename) throws Exception {
dirFile.mkdirs();
File file = null;
try {
item.write(file);
return file;
} catch (IOException e) {
// ... tratamento específico para estes tipos de exceção
}
}
Completion
Your try-catch
accepted other types than Exception but due to a (probably bad) decision of the method developer Fileitem.write, you will need to treat Exception also in addition to treating the most specific exception you want.
Good attitude. What exception do you want to specify? And what happens when you do this?
– Maniero