What exceptions should I catch in a try-catch?

1

I have some questions in try catch regarding which types of exceptions to put. This example would be the best option?

try {
    String folerPath = Environment.getExternalStorageDirectory() + File.separator + "Folder" + File.separator;
    File dir = new File(folderPath);
    deleteDirectory(dir);
} catch (Qual exceção?){

}
    
asked by anonymous 11.09.2015 / 15:33

2 answers

0

Friend, if you need to handle the exceptions separately, I recommend using try catch threaded, follow an example below:

try {
// código

}catch (Excecao1 ex) {
//Tratamento da excecao 1
}

catch (Excecao2 ex) {
//Tratamento da excecao 2
}

If you do not need to treat separately, just use the generic exceptions class.

    
11.09.2015 / 15:39
9

Always look at the documentation of all methods used to see what the possible exceptions are and decide which you can handle effectively, that is, you can solve the problem.

Environment.getExternalStorageDirectory() indicates no exception.

File() can generate NullPointerException however this is a programming error and should not be treated in a specific way. There is nothing that can be done to solve this at runtime, just fix the program.

deleteDirectory() seems to be something from your code, so having to see inside it can lead to exceptions.

I would not use a try-catch there, but would probably use within this deleteDirectory() . There are probably other types of errors that can be important.

In a larger context of the code I could change my mind and say that I have to handle more generic exceptions. In general this should not be done in specific codes but there may be case. It's almost certain that not should do this there but there is a case that capturing a Exception overall can be useful.

In fact there is an abuse of try-catch , most of them in codes are not required. Some hinder the operation of the application or at least the detection of problems. In general people use it thinking that this solves existing problems when in fact it only hides them. Sometimes they use it because they think it should be used without knowing why.

I talk about this in various answers here at SOpt . Read everything you can about it, even if it's not about Java or Android. Not only what I wrote and the material found here on the site. It is very important to know how to use this correctly.

    
11.09.2015 / 16:04