Given the following piece of code:<br><pre><code class="java">class SalaryCalculationException extends Exception{}class Person{ public void calculateSalary() throws SalaryCalculationException{ //... throw new SalaryCalculationException(); //... }}class Company{ public void paySalaries(){ new Person().calculateSalary(); }}</code></pre><br>Which of the following statements is correct?<br>1. This code will compile without any problems.<br>2. This code will compile if in method paySalaries() we return a boolean in stead of void.<br>3. This code will compile if we add a try-catch block in paySalaries().<br>4. This code will compile if we add throws SalaryCalculationException in the signature of method paySalaries().
Correct Answer: 3 and 4
1. This code will compile without any problems.
This statement is incorrect because the code includes the declaration of a checked exception (
2. This code will compile if in method
This statement is incorrect because the issue with the compilation lies in the exception handling, not the return type of the
3. This code will compile if we add a try-catch block in
This statement is correct. By adding a try-catch block in the
4. This code will compile if we add
This statement is correct. By adding the
Therefore, the correct statement is D. 3 and 4.
This statement is incorrect because the code includes the declaration of a checked exception (
SalaryCalculationException
), but it is not handled or propagated properly. So, it will not compile without addressing this issue.2. This code will compile if in method
paySalaries()
we return a boolean instead of void.This statement is incorrect because the issue with the compilation lies in the exception handling, not the return type of the
paySalaries()
method. Changing the return type to boolean
will not resolve the compilation problem.3. This code will compile if we add a try-catch block in
paySalaries()
.This statement is correct. By adding a try-catch block in the
paySalaries()
method, we can catch the SalaryCalculationException
thrown by the calculateSalary()
method. This way, the exception is properly handled, and the code will compile successfully.4. This code will compile if we add
throws SalaryCalculationException
in the signature of method paySalaries()
.This statement is correct. By adding the
throws SalaryCalculationException
clause to the paySalaries()
method signature, we indicate that this method may throw the SalaryCalculationException
. This way, the exception is propagated to the caller, and the code will compile successfully.Therefore, the correct statement is D. 3 and 4.