Consider the following code:
class Main { //from w ww . j a va 2s.co m public void doMain (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) { doMain (15); // 3 } else return; } public static void main (String [] args) { // 4 Main a = new Main (); a.doB (args.length>0); // 5 } }
Which of the following statements are correct?
Select 1 option
Correct Option is : D
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, doMain()
declares that it throws Exception.
doB () is calling doMain but it is not handling the exception generated by doMain ().
So, it must declare that it throws Exception.
Now, the main () method is calling doB (), which generates an exception.
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 bubble up to.
After that the exception is thrown to the JVM and the JVM kills the thread.