About Question com.enthuware.jfcja.v8.2.254 :
Posted: Sun Feb 14, 2021 10:31 am
The answer to this is supposedly: This will compile if 'throws Exception' is added at line //2 as well as //4. I pasted this into my IDE and it compiles with no compiler error.
Consider the following code ...
class A
{
public void doA(int k) throws Exception { // 0
for(int i=0; i< 10; i++) {
if(i == k) throw new Exception("Index of k is "+i); // 1
}
}
public void doB(boolean f) { //2
if(f) {
doA(15); //3
}
else return;
}
public static void main(String[] args) { //4
A a = new A();
a.doB(args.length>0); //5
}
}
The explanation is given was: Any checked exceptions must be either handled using a try block, or the method that generates the exception must declare that it throws that exception.
In this case, doA() declares that it throws "Exception". doB() is calling doA but it is not handling the exception generated by doA(). So, it must declare that it throws "Exception". Now, the main() method is calling doB(), which generates an exception (due to a call to doA()). Therefore, main() must also either wrap the call to doB() in a try block or declare it in its throws clause.
The main(String[] args) method is the last point in your program where any unhandled checked exception can boil up to. After that the exception is thrown to the JVM and the JVM kills the thread.
Consider the following code ...
class A
{
public void doA(int k) throws Exception { // 0
for(int i=0; i< 10; i++) {
if(i == k) throw new Exception("Index of k is "+i); // 1
}
}
public void doB(boolean f) { //2
if(f) {
doA(15); //3
}
else return;
}
public static void main(String[] args) { //4
A a = new A();
a.doB(args.length>0); //5
}
}
The explanation is given was: Any checked exceptions must be either handled using a try block, or the method that generates the exception must declare that it throws that exception.
In this case, doA() declares that it throws "Exception". doB() is calling doA but it is not handling the exception generated by doA(). So, it must declare that it throws "Exception". Now, the main() method is calling doB(), which generates an exception (due to a call to doA()). Therefore, main() must also either wrap the call to doB() in a try block or declare it in its throws clause.
The main(String[] args) method is the last point in your program where any unhandled checked exception can boil up to. After that the exception is thrown to the JVM and the JVM kills the thread.