Given:
public class Main {
public static void main(String[] args) {
doSomething();
}
private static void doSomething() {
doSomeThingElse();
}
private static void doSomeThingElse() {
throw new Exception();
}
}
Which approach
ensures that the class can be compiled and run?
A.
Put the throw new Exception() statement in the try block of try ‘ catch
Put the throw new Exception() statement in the try block of try ‘ catch
B.
Put the doSomethingElse() method in the try block of a try ‘ catch
Put the doSomethingElse() method in the try block of a try ‘ catch
C.
Put the doSomething() method in the try block of a try ‘ catch
Put the doSomething() method in the try block of a try ‘ catch
D.
Put the doSomething() method and the doSomethingElse() method in the try block of a try ‘ catch
Put the doSomething() method and the doSomethingElse() method in the try block of a try ‘ catch
Risposta A
:
private static void doSomeThingElse() {
try {
throw new Exception();
} catch (Exception e)
{
e.printStackTrace();
}
}
Un’altra possibilità non contemplate qui è quella di
aggiungere i trhown in tutti i metodi chiamanti :
public static void main(String[] args) throws Exception {
doSomething();
}
private static void doSomething() throws Exception {
doSomeThingElse();
}
private static void doSomeThingElse() throws Exception {
throw new Exception();
}
Nessun commento:
Posta un commento