Doubt between try-catch and throws

1

When I write .start () in the code to indicate that the process starts, the Eclipse program gives me an error and gives me two options: wrap the .start () in a try-catch block or add a throws to the class. What is the difference between using a try-catch block to wrap a code and putting a throw in the class?

    
asked by Sergio AG 28.05.2018 в 01:02
source

1 answer

2

A method can only throw a checked exception if it is declared with the throws clause. In this way, a code that uses this method knows that it is possible that the exception is thrown during the call to it.

So, if metodoA calls metodoB and metodoB has, eg throws FileNotFoundException , the compiler knows there are two options:

  • metodoA does not address the possible exception. When metodoB throws the exception, in turn metodoA will propagate the exception to the method that invokes it. Therefore, because of the above, metodoA can throw the exception, so you need to declare it in your throws .

  • The call to metodoB is within a try/catch that captures the exception defined in throws and does not re-launch it. Since there is no risk that metodoA throw the exception, you do not need to declare it in your throws clause.

answered by 28.05.2018 в 13:00