Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between try-catch and throw in java

Tags:

java

exception

What is the difference between try-catch and throw clause. When to use these?

Please let me know .

like image 580
user393043 Avatar asked Sep 25 '10 18:09

user393043


People also ask

Which is better try-catch or throws?

From what I've read myself, the throws should be used when the caller has broken their end of the contract (passed object) and the try-catch should be used when an exception takes place during an operation that is being carried out inside the method.

What is difference between throw and throws in Java?

The throw keyword is used to throw an exception explicitly. It can throw only one exception at a time. The throws keyword can be used to declare multiple exceptions, separated by a comma. Whichever exception occurs, if matched with the declared ones, is thrown automatically then.

Can we use try-catch with throws?

4. throws: The throws keyword is used for exception handling without try & catch block.

What is throw and throws in Java with example?

Definition. Throw is a keyword which is used to throw an exception explicitly in the program inside a function or inside a block of code. Throws is a keyword used in the method signature used to declare an exception which might get thrown by the function while executing the code.


1 Answers

  • The try block will execute a sensitive code which can throw exceptions
  • The catch block will be used whenever an exception (of the type caught) is thrown in the try block
  • The finally block is called in every case after the try/catch blocks. Even if the exception isn't caught or if your previous blocks break the execution flow.
  • The throw keyword will allow you to throw an exception (which will break the execution flow and can be caught in a catch block).
  • The throws keyword in the method prototype is used to specify that your method might throw exceptions of the specified type. It's useful when you have checked exception (exception that you have to handle) that you don't want to catch in your current method.

Resources :

  • oracle.com - Lesson: Exceptions

On another note, you should really accept some answers. If anyone encounter the same problems as you and find your questions, he/she will be happy to directly see the right answer to the question.

like image 63
Colin Hebert Avatar answered Oct 05 '22 22:10

Colin Hebert