try { //в этом блоке мы пишем код, где может возникнуть ошибка }catch(Exception e){ // тут если выскакивает ошибка мы пишем код, который должен выполнится и Приложение закрывается?? }finally { //код который выполнится независимо от того, будет ли исключение или не будет. } 

Ie, if an exception is thrown, the code from the catch block is executed first, and then from the finally

If the exception did not crash, then the code is executed from the finally block?

As I understand correctly, that is, in order for the Application not to close on an error, then you need to do everything to stop this error in the catch and continue executing the program code in the finally block?

  • 2
    In general, yes, but it is possible without finally - rjhdby

1 answer 1

In try there is a code in which Exception can occur.

In the catch (..) block, there is a code that somehow handles the error (possibly and closes the application or Activity, if necessary)

The finally block is always called (both when an error occurred and when it did not). try, catch can be implemented without a finally block.

There can be more than one catch block. Each error has its own block, for example:

 try{ code...} catch (FileNotFoundException e) { code... } catch (IOExeption e){ code... } finally { code... } 

This is necessary in order to handle various errors necessary for them.

  • An example is bad. FileNotFoundException never rolls being extends IOException (update: the answer is changed, the tension is removed). + since such an answer can be mentioned try with resources - Andrey M
  • @AndreyM Thanks for the comment. Changed the order of ketches, now FileNotFoundException will be caught. - Valery Ponomarenko