nerdexam
Oracle

1Z0-805 · Question #63

Given the code fragment: / method declaration / { try { String className = "java.lang.String"; String fieldname = "somefield"; Class c = Class.forName(className); Field f = c.getField(fieldname); }…

The correct answer is C. public void getMetadata () throws Exception E. public void getMetadata () throws classNotFoundException. We must specify that the getMetaData method can throw both ClassNotFoundException (line Class c = Class.forName(className);) and a NoSuchFieldException (line Field f = c.getField(fieldname);). We can do this by either declare that all exception can be thrown or that these two…

Exceptions and Assertions

Question

Given the code fragment:

/* method declaration */ { try { String className = "java.lang.String"; String fieldname = "somefield"; Class c = Class.forName(className); Field f = c.getField(fieldname); } catch(Exception e) {

Options

  • Apublic void getMetadata ()
  • Bpublic void getMetadat ()
  • Cpublic void getMetadata () throws Exception
  • Dpublic void getMetadata () throws NoSuchFieldException
  • Epublic void getMetadata () throws classNotFoundException
  • Fpublic void getMetadata () throws ClassNotFoundException, NoSuchFieldException.

How the community answered

(18 responses)
  • A
    17% (3)
  • B
    6% (1)
  • C
    72% (13)
  • F
    6% (1)

Explanation

We must specify that the getMetaData method can throw both ClassNotFoundException (line Class c = Class.forName(className);) and a NoSuchFieldException (line Field f = c.getField(fieldname);). We can do this by either declare that all exception can be thrown or that these two specific exceptions can be thrown Oracle 1Z0-805 Exam Note: Valid Java programming language code must honor the Catch or Specify Requirement. This means that code that might throw certain exceptions must be enclosed by either of the * A try statement that catches the exception. The try must provide a handler for the exception. * A method that specifies that it can throw the exception. The method must provide a throws clause that lists the exception. Code that fails to honor the Catch or Specify Requirement will not compile.

Topics

#reflection#exception handling#checked exceptions#Class.forName

Community Discussion

No community discussion yet for this question.

Full 1Z0-805 Practice