mercoledì 6 novembre 2013

Q36


Given the code fragment:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
 

class Base {
     public void process() throws IOException {
          FileReader fr = new FileReader ("userguida.txt");
          BufferedReader br = new BufferedReader (fr);
          String record;
          while ((record = br.readLine())!=null){
                System.out.println(record);
          }
     }
}

public class Derived extends Base {
     public void process() throws Exception {
          super.process();
          System.out.println("process");
     }

     public static void main (String[] args){
          try {
                new Derived.process();
          } catch (Exception e) {
                System.out.println(e.getClass());
          }
     }
}

 
If the file userguide.txt does not exist, what is the result?

A.
An empty file is created and success is printed.


B.
class java.io.FileNotFoundException.


C.
class java.io.IOException.


D.
class java.lang.Exception.


E.
Compilation fails.



La risposta è E .

Ci si aspetta che le istanze della classe Base aderiscano al contratto dichiarato, quindi che process aderisca alla clausola trhows IOException . Sovrascrivendo process e cambiando l’eccezione con una più alta si ha la rottura del contratto e anche la violazione del principio di sostituzione di Liskov.

Multiple markers at this line
            - Exception Exception is not compatible with throws clause in Base.process()
            - overrides Base.process

Se invece il metodo che sovrascrive avesse utilizzato una eccezione più bassa del metodo padre il codice avrebbe compilato :

class Base {
     public void process() throws Exception  { ...
public void process() throws IOException { ...

In questo caso ovviamente si avrebbe avuto un errore all’invocazione del super : Unhandled exception type Exception
 

Nessun commento:

Posta un commento