Exception Java | SoloLearn: Learn to code for FREE!

+3

Exception Java

How do you choose between try/catch or Throws ?

8/7/2019 2:24:41 PM

Supergirl

22 Answers

New Answer

+3

ok many thanks 😊

+3

Try and catch: The try block contains set of statements that can occur an exception. Place the code in try block that might throw an exception. If an exception occurs in try block for a statement, then the rest code will not be executed which placed in same block. When an exception is occurred in try block it will be handling by catch block. Catch block is used to handle the occurred exceptions. To use the catch block you must declare the type of exception within the parameter. https://javagoal.com/try-and-catch-block/ throw: The throw keyword is used to throw an exception from a method or block of code. If you want to throw an exception on basis of certain conditions, you can use throw keyword. For example, if a user entered NULL/BLANK password we should throw exception to client. We can throw either checked or unchecked exception. https://javagoal.com/throw/

+2

thanks for your answer 😊 so if I well understand you choose try/catch when you are sure exception will occur

+2

+1

I choose try/catch when I am not shure what exactly will happen. For example everything outside my program like user input, load/save files, connection to database or a server.... You can always read the docomentation (java doc or whatever libary u r using) to check what exceptions can occure.

+1

Please come in chat

+1

+1

Update app. In notifications there will be mesaages. In that mesaage me

+1

+1

many thanks 😊

+1

pourquoi se venger ??? sur qui?

+1

it was for Java chalenges. I've lost against somebody yesterday

+1

Thanks Very clear explanations !!!

+1

You use try when something may go wrong later, for example, using a audio file from external source, like this : https://code.sololearn.com/Wl23AIEG6SuZ/?ref=app Because the website may break down, or they remove the mp3 files. We use try-catch when loading the audio, and don't forget to use try-catch when trying the audio too (line 114 and 123). throw is similar to assertion, for example, a program only for 18 years old or above, and the user entered that his age is 16, now you can use throw to raise an error to terminate the program and give the user a warning.

+1

Many thanks for explanations 😊

0

Use try/catch to handle existing exceptions. And use throws to generate a new exception.

0

0

Try catch is used when you want to catch and handle the exception. Throws is used to propagate the exception to the caller of the method then the caller will handle that exception..

0

Je prendrais ma revenge

0

Supergirl no problem ;) keep up learning 💪