Android Question When to use try/Catch block ?

Devv

Active Member
Licensed User
Longtime User
As the tile say
when i have to us the try and catch block ?
is it safer to use it in every function (to avoid forced closed)
vibrating or toasting does need try block ?

any info is highly appreciated
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
is it safer to use it in every function (to avoid forced closed)
No.
You will break a very important concept which is to let your program "fail fast". You should only catch exceptions in cases that are out of your control and can fail.

For example if the user enters text and you need to parse it.
 
Upvote 0

Devv

Active Member
Licensed User
Longtime User
No.
You will break a very important concept which is to let your program "fail fast". You should only catch exceptions in cases that are out of your control and can fail.

For example if the user enters text and you need to parse it.

What will happen if i did too many try blocks ?
can you give me more examples ?
 
Upvote 0

ilan

Expert
Licensed User
Longtime User
What will happen if i did too many try blocks ?
can you give me more examples ?

If you enter itry..catch in every sub you will never know when your code does not work correctly.

Different phones/android versions could give crash on a specific sub that you will not see on your phone and thats because something is missing or done not correctly and your app will not work the same on other phones like it does on yours.

Its important to get the crash report to check what could be wrong in your code

Example:

You want to use a value from a saved file in your dirinternal directory, the first time you tried it while developing you had a crash because the file was not available so you created it and keep developing and forget to write

if file.exists()... then

And now on new install those values would be blank and no error will be displayed because this code is between try... catch
 
Last edited:
Upvote 0
Top