About Question com.enthuware.jfcja.v8.2.254 :

Oracle Certified Foundations Associate Java Certification Questions and Discussion
1Z0-811

Moderator: admin

Post Reply
qmcgreer
Posts: 2
Joined: Fri Feb 12, 2021 10:58 am
Contact:

About Question com.enthuware.jfcja.v8.2.254 :

Post by qmcgreer »

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.

admin
Site Admin
Posts: 10036
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: About Question com.enthuware.jfcja.v8.2.254 :

Post by admin »

No, it doesn't compile. Check carefully. The line doA(15); //3 will cause an error.
Due to various optimizations and ease of use features, the errors and warnings shown by an IDE are not always consistent with what you see with the command line java/javac tools. So, we do not recommend the use of an IDE while learning.
Use notepad/notepad++ and command line to compile and run the code.
If you like our products and services, please help us by posting your review here.

Post Reply

Who is online

Users browsing this forum: No registered users and 19 guests