Question: Intro to java ( exceptions chapter) 1. Correct the following method definition by adding a suitable throws clause: (5 POINTS) public void doStuff(int n) {

Intro to java ( exceptions chapter)

1. Correct the following method definition by adding a suitable throws clause: (5 POINTS)

public void doStuff(int n) { if (n < 0) throw new Exception("Negative number."); }

2. What happens if you invoke a method and it throws a checked exception that it does not catch? (5 POINTS)

3. What output will be produced by the following code? The definition of the class NegativeNumberException is given in the preceding material, but you do not need to look at it to answer this question.

try { int n = 7; if (n > 0) throw new Exception(); else if (n < 0) throw new NegativeNumberException(); else System.out.println("Hello!"); } catch(NegativeNumberException e) { System.out.println("First catch."); } catch(Exception e) { System.out.println("Second catch"); } System.out.println("End of code");

4. Repeat Question 3, but change the value of n from 7 to ?7. (5 POINTS)

5. Repeat Question 3, but change the value of n from 7 to 0. (5 POINTS)

6. What output is produced by the following program? (5 POINTS)

public class Question30 { public static void main(String[] args) { Question30 object = new Question30(); try { System.out.println("Trying"); object.sampleMethod(); System.out.println("Trying after call."); } catch(Exception e) { System.out.println("Catching"); System.out.println(e.getMessage()); } } public void sampleMethod() throws Exception { System.out.println("Starting sampleMethod."); throw new Exception("From sampleMethod with love."); } }

7. Consider the following program:

public class Question33 { public static void main(String[ ] args) { try { sampleMethod(99); } catch(Exception e) { System.out.println("Caught in main."); } } public static void sampleMethod(int n) throws Exception { try { if (n > 0)throw new Exception(); else if (n < 0) throw new NegativeNumberException(); else System.out.println("No exception."); System.out.println("Still in sampleMethod."); } catch (NegativeNumberException e) { System.out.println("Caught in sampleMethod."); } finally { System.out.println("In finally block."); } System.out.println("After finally block."); } }

a. What output does the program produce? (5 POINTS)

b. What output would the program produce if the argument to sampleMethod were ?99 instead of 99? (5 POINTS)

c. What output would the program produce if the argument to sampleMethod were 0 instead of 99? (5 POINTS)

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!