What is the difference between try-catch and throw clause. When to use these?
Please let me know .
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.
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.
4. throws: The throws keyword is used for exception handling without try & catch block.
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.
try
block will execute a sensitive code which can throw exceptionscatch
block will be used whenever an exception (of the type caught) is thrown in the try blockfinally
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.throw
keyword will allow you to throw an exception (which will break the execution flow and can be caught in a catch
block).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 :
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With