When to use try- catch statments...
ekte spiriopoulos wrote:
you solve it thank you.If it is not problem when i should use try-catch any example? on this exercise to understand it i will appreciate it
Shaun Wild wrote:I'm not 100% sure what you're asking but I'm going to make some assumptions...
You want to throw an exception if ?
If so you need only do:
try-catch statements are used for catching thrown exceptions - not for throwing exceptions!
If a method throws an exception (specified with the throws keyword), you must either encapsulate any calls to that method in a try- catch or ensure that the method that is calling it throws the same exception. For example, in Java, Thread.sleep(long ms) is a function that throws an InterruptedException. So to call it you must encapsulate it in a try- catch as follows:
You can also make sure taht the method calling it throws the same exception too:
Just bare in mind that any method calling sleep(ms) would have to encapsulate sleep in a try- catch.