Question

Please help me answer these questions in java programming language. Please answer it line after line...

Please help me answer these questions in java programming language. Please answer it line after line so that I can understand please.

Does it compile or not?
No programming is done in this exercise, simply answer the questions asked in the code given
below.


class Exemple {
/*Explain why this code does not compile
*/
public void m1() {
foo();
}
public int foo() throws Exception {
throw new Exception();
}
/*Explain why this code is not considered as good
*/
public void m2() {
try {
//do stuff...
} catch (Exception e) {
} }
/* Explain why this code does not compile
*/
public void m3() {
try {
//do stuff...

} catch (Exception e) {
} catch (NullPointerException e) {

} }

/* Explain why this code does not compile
*/
public void m4() {
throw new CustomCheckedException();
}
private class CustomCheckedException extends Exception {
private static final long serialVersionUID = -7944813576443065516L;
public CustomCheckedException() {
//nothing
} }
/* Explain why this code does not compile
*/
public int m5() {
int age;
String s = "24";
try {
age = getAccessCode();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return age;
}
public int getAccessCode() throws IllegalAccessException {
throw new IllegalAccessException();
}
/* Explain why this code COMPILES */
public void m6() {
bar();
}
public int bar() {
throw new RuntimeException();
} }

0 0
Add a comment Improve this question Transcribed image text
Answer #1

class Exemple {
/*Explain why this code does not compile
* Ans : method foo() declars that it will throw Exception. so any method which calling foo()
* have to write it in try and catch block or it can declare throw Exception in method definition
* other wise it will throw compile time error
* so correct implementation is
* public void m1() throws Exception{
foo();
}
or
public void m1() {
try {
       foo();
   } catch (Exception e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
   }
}
*/
public void m1() {
  
       foo();
  
}
public int foo() throws Exception {
   throw new Exception();
}
}

/*Explain why this code is not considered as good

Here Exception being caught is of type Exception. This is the parent of all Exceptions. There no way to find out exactly what type of exception is being caught here like IOException, SqlException. It reduces the readability of the program.
*/
public void m2() {
try {
//do stuff...
} catch (Exception e) {
} }

/* Explain why this code does not compile

Ans : In catch block , Exception is being caught first then NullPointerException. NullPointerException is sub-class of Exception class. The rule is sub-class Exception should be caught first then parent. that's why this program won't compile.
*/
public void m3() {
try {
//do stuff...

} catch
} catch
(Exception e) {
(NullPointerException e) {

} }

/* Explain why this code does not compile

Ans : There are two errors in this snnipet.

1. while declaring class only public, abstract & final are permitted. But here private given.

2. m4() throws new CustomCheckedException() exception, but neither it is adding try-catch or it is declaring CustomCheckedException using throws
*/
public void m4() {
throw new CustomCheckedException();
}
private class CustomCheckedException extends Exception {
private static final long serialVersionUID = -7944813576443065516L;
public CustomCheckedException() {
//nothing
} }

/* Explain why this code does not compile
   * Ans: Local must be initialized in java, before using it. Age here is not initialized thats' why this
   * error is coming.
   */
   public int m5() {
   int age;
   String s = "24";
   try {
   age = getAccessCode();
   } catch (IllegalAccessException e) {
   e.printStackTrace();
   }
   return age;
   }
   public int getAccessCode() throws IllegalAccessException {
   throw new IllegalAccessException();
   }

/* Explain why this code COMPILES
   * Ans: RuntimeException It is a system Exception.
   * it is not recoverable
   * So we don't write try-catch or throws
   * */
   public void m6() {
   bar();
   }
   public int bar() {
           throw new RuntimeException();
   }
  

Add a comment
Know the answer?
Add Answer to:
Please help me answer these questions in java programming language. Please answer it line after line...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Question 5 (10 points) Assume you have the following code, with blanks to be filled in...

    Question 5 (10 points) Assume you have the following code, with blanks to be filled in below. public static void g () ( throw new () public static void f() try ) catch ( 12), e) System.out.print ("A") ; return } catch ( System.out. print ("B") throw ei e) ( 13) catch ( 14) e) ( System.out.print ("C") ; } finally System.out.print ("D") ; System.out.print ("E") ; } public static void main (String (] args) try f() } catch (...

  • Need help with writing a Client test in JAVA

    public class TutorialSpace {                  // slots — the number of available slots in a tutorial class         private int slots;         // activated — true if the tutorial class has been activated         private boolean activated;                  /**         * TutorialSpace(n) — a constructor for a tutorial class with n slots.         *          * @param n         */         public TutorialSpace(int n) {                 this.slots = n;                 this.activated = false;         }                  /**         * activate() — activates the tutorial class. Throws an exception if the         * tutorial class has already been activated.         *          * @throws NotActivatedException         */                  public void activate() throws NotActivatedException {                 if (activated) {                         throw new NotActivatedException("Already Activated");                 } else {                         activated = true;                 }         }                  /**         * reserveSlot()—enrol a student into the tutorial class by decreasing the         * number of slots left for enrolling in the class. Throws an exception if slot         * is either completely used or the tutorial class is not active.         *          * @throws EmptyException         */         public void reserveSlot() throws EmptyException {                                  if (!activated || slots == 0) {                         throw new EmptyException("Tutorial space is empty");                 } else {                         slots--;                 }         }                  /**         * slotsRemaining()—returns the number of slots remaining in the tutorial class.         */                  public int slotsRemaining() {                 return slots;         }          } public class NotActivatedException extends Exception {                  /**         *          */         private static final long serialVersionUID = 1L;                  public NotActivatedException(String msg) {                 super(msg);         }          } public class EmptyException extends Exception {                  /**         *          */         private static final long serialVersionUID = 1L;         public EmptyException(String msg) {                 super(msg);         }                  ...

  • Please help me to answer the 5 programming questions and give some specific explanations, thanks a...

    Please help me to answer the 5 programming questions and give some specific explanations, thanks a lot !!! Question Consider a class hierarchy that includes a class called Creature, with subclasses called Unicorn and Dragon. The Creature class has a method called feelsLike, Not yet answered which is overridden in the Unicorn and Dragon class. Marked out of The feelsLike method of the Creature class returns "smooth", while the feelsLike method is overridden in the Unicorn class to return "fluffy"...

  • Can you plz help me this in java? QUESTION 14 Given public static void test() throws...

    Can you plz help me this in java? QUESTION 14 Given public static void test() throws FileNotFoundException{ try { throw FileNotFoundException(); } finally { Determine why it will not compile. Which statement(s) is(are) correct? (Choose all that apply) A. The code will not compile without a catch clause UB. The finally clause should be the final clause UC There is no class called FileNotFoundException D. None of these

  • Please help me do the java project For this project you will be reading in a...

    Please help me do the java project For this project you will be reading in a text file and evaluating it in order to create a new file that represents the Class that will represent the properties of the text file. For example, consider the following text file: students.txt ID              Name                              Age                    IsMale           GPA 1                Tom Ryan                       22                       True              3.1 2                Jack Peterson                31                       True              2.7 3                Cindy LuWho                12                       False             3.9 When you read in the header line, you...

  • iImplement a Singly Linked List detectLoop in Java, it would check whether the linked list contains...

    iImplement a Singly Linked List detectLoop in Java, it would check whether the linked list contains a loop. Print true if yes, false if not. Test by using the following code: LL<Integer> L = new LL<>(); for (int i = 1000; i > 0; i-=3) sl.add(i); try { L.insert(122, L.getNode(70), L.getNode(21)); if (L.detectLoop()) System.out.println("True"); else System.out.println("False."); } catch(Exception e){ e.printStackTrace(); } class Linkedlist<E>{ private static class Node<E>{ private E element; private Node<E> next; public Node(E e, Node<E> n){ element =...

  • 2. Write MinheapPriorityQueue constructor, which takes an array of data, and construct the max heap priority...

    2. Write MinheapPriorityQueue constructor, which takes an array of data, and construct the max heap priority queue using bottom-up algorithm. The expected run time should be O(n), where n is the total number of data. BubbleDown method is provided. You may test it in this minHeap public class MinHeapPriorityQueue<E extends Comparable<? super E>>{ private E data[]; private int size; public MinHeapPriorityQueue(){ this(100); } public MinHeapPriorityQueue(int cap){ size = 0; data = (E[]) new Comparable[cap]; } public MinHeapPriorityQueue(int[] a){ } public...

  • Using java socket programming rewrite the following program to handle multiple clients simultaneously (multi threaded programming)...

    Using java socket programming rewrite the following program to handle multiple clients simultaneously (multi threaded programming) import java.io.*; import java.net.*; public class WelcomeClient { public static void main(String[] args) throws IOException {    if (args.length != 2) { System.err.println( "Usage: java EchoClient <host name> <port number>"); System.exit(1); } String hostName = args[0]; int portNumber = Integer.parseInt(args[1]); try ( Socket kkSocket = new Socket(hostName, portNumber); PrintWriter out = new PrintWriter(kkSocket.getOutputStream(), true); BufferedReader in = new BufferedReader( new InputStreamReader(kkSocket.getInputStream())); ) { BufferedReader...

  • Can someone help me to figure that error I have put below. JAVA ----jGRASP exec: javac...

    Can someone help me to figure that error I have put below. JAVA ----jGRASP exec: javac -g P4Program.java P4Program.java:94: error: package list does not exist Iterator i = new list.iterator(); ^ 1 error ----jGRASP wedge2: exit code for process is 1. ----jGRASP: operation complete. Note: Below there are two different classes that work together. Each class has it's own fuctions/methods. import java.util.*; import java.io.*; public class P4Program{ public void linkedStackFromFile(){ String content = new String(); int count = 1; File...

  • Question 10 (3 points) Which of the following statement is not true? There is a recursive...

    Question 10 (3 points) Which of the following statement is not true? There is a recursive sum method as shown below. When sum (19) is called, summation of all odd numbers less than 19 will be calculated and returned public int sum(int x){ if (x == 0) return 0: else return sum(x-2) + x; The following code segment will throw a testException. This exception has been handled in the way that do nothing but to continue when this exception happens....

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT