Examveda
Examveda

Given the following piece of code:
class SalaryCalculationException extends Exception{}
class Person{
        public void calculateSalary() throws SalaryCalculationException{
                //...
                throw new SalaryCalculationException();
                //...
        }
}
class Company{
        public void paySalaries(){
                new Person().calculateSalary();
        }
}

Which of the following statements is correct?
1. This code will compile without any problems.
2. This code will compile if in method paySalaries() we return a boolean in stead of void.
3. This code will compile if we add a try-catch block in paySalaries().
4. This code will compile if we add throws SalaryCalculationException in the signature of method paySalaries().

A. 1 and 4

B. 2 and 3

C. 2 and 4

D. 3 and 4

E. 1 and 2

Answer: Option D

Solution(By Examveda Team)

1. This code will compile without any problems.
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.

This Question Belongs to Java Program >> Exceptions

Join The Discussion

Comments ( 1 )

  1. S Sarath
    S Sarath :
    10 months ago

    can anyone plz tell me the reason for option D

Related Questions on Exceptions