CCNA Exceptions Tools Questions

61 questions · Exceptions Tools topic · All types, answers revealed

1
MCQhard

A method declares throws FileNotFoundException and SQLException. Which statement about the caller is true?

A.The caller must catch only FileNotFoundException.
B.The caller can declare throws Exception to cover both.
C.The caller must handle or declare both exceptions.
D.The caller can ignore both exceptions.
AnswerC

Each checked exception must be handled or declared.

Why this answer

Option C is correct because in Java, when a method declares checked exceptions (like FileNotFoundException and SQLException) in its throws clause, any caller must either handle each checked exception with a try-catch block or declare them in its own throws clause. The compiler enforces this rule to ensure that checked exceptions are properly accounted for, preventing unhandled checked exceptions from propagating unchecked.

Exam trap

The trap here is that candidates often think they can choose to handle only one exception or ignore checked exceptions entirely, forgetting that Java's checked exception mechanism requires every declared checked exception to be either caught or re-declared by the caller.

How to eliminate wrong answers

Option A is wrong because the caller cannot catch only FileNotFoundException; it must handle or declare both checked exceptions (FileNotFoundException and SQLException) as they are both declared in the method's throws clause. Option B is wrong because while the caller can declare throws Exception to cover both, this is not the only option; the caller could also handle them individually with catch blocks, and the statement 'can declare throws Exception' is true but does not represent the mandatory requirement that the caller must handle or declare both. Option D is wrong because ignoring both exceptions is not allowed; the Java compiler will produce a compilation error if the caller does not handle or declare the checked exceptions.

2
MCQmedium

A developer is using the Oracle Java Platform Debugger Architecture (JPDA) to debug a remote Java application. Which command-line option is required to start the application in debug mode listening on port 5005?

A.-javaagent:debug.jar=port=5005
B.-Xdebug -Xrunjdwp:transport=dt_socket,server=y,address=5005
C.-Ddebug=true -Dport=5005
D.-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005
AnswerD

This is the correct and current syntax for enabling debugging with JDWP.

Why this answer

Option D is correct because the `-agentlib:jdwp` option is the modern, recommended way to enable the Java Debug Wire Protocol (JDWP) for remote debugging. It specifies the transport as `dt_socket` (TCP/IP sockets), sets the JVM as the debug server (`server=y`), does not suspend the application on startup (`suspend=n`), and listens on port 5005 (`address=5005`). This is the standard JPDA configuration for attaching a debugger to a running Java application.

Exam trap

Oracle often tests the distinction between deprecated `-Xdebug -Xrunjdwp` and the modern `-agentlib:jdwp` syntax, and candidates may mistakenly choose the deprecated option because it was widely used in older Java versions.

How to eliminate wrong answers

Option A is wrong because `-javaagent` is used to specify a Java agent JAR file for instrumentation (e.g., profilers or APM tools), not for enabling JDWP debugging; there is no standard `debug.jar` that provides JDWP functionality. Option B is wrong because `-Xdebug` and `-Xrunjdwp` are deprecated in modern Java versions (Java 9+), and the `-Xrunjdwp` syntax is no longer supported; the correct approach uses `-agentlib:jdwp`. Option C is wrong because `-Ddebug=true -Dport=5005` sets system properties that have no effect on JDWP; the JVM does not interpret these properties to enable debugging.

3
MCQhard

A Java application uses a custom exception class that extends Exception. The application throws this exception from a method, but the method does not declare it in its throws clause. Which statement is true?

A.The code will not compile because checked exceptions must be declared.
B.The code will compile only if the exception is caught inside the method.
C.The code will compile and throw a RuntimeException if the exception occurs.
D.The code will compile because custom exceptions are unchecked.
AnswerA

Checked exceptions (those extending Exception but not RuntimeException) must be declared in the throws clause or caught within the method.

Why this answer

In Java, a custom exception class that extends Exception (but not RuntimeException) is a checked exception. Checked exceptions must be either caught within the method using a try-catch block or declared in the method's throws clause. If the method throws a checked exception without declaring it, the code will not compile.

This is enforced by the Java compiler to ensure that callers are aware of and handle potential exceptions.

Exam trap

The trap here is that candidates often confuse custom exceptions as automatically unchecked, forgetting that only exceptions extending RuntimeException or Error are unchecked; any class directly extending Exception is a checked exception and must be declared or caught.

How to eliminate wrong answers

Option B is wrong because catching the exception inside the method would handle it, but the question states the exception is thrown and not declared; if it is caught, it is not thrown to the caller, so the throws clause is unnecessary, but the scenario says 'throws this exception from a method' implying it propagates. Option C is wrong because a custom exception extending Exception is a checked exception, not a RuntimeException; it will not be automatically wrapped or converted to a RuntimeException, and the code will not compile. Option D is wrong because custom exceptions that extend Exception (not RuntimeException) are checked exceptions, not unchecked; unchecked exceptions extend RuntimeException or Error.

4
MCQeasy

Which tool is used to generate documentation comments from Java source code?

A.javac
B.java
C.javadoc
D.jar
AnswerC

Javadoc extracts comments formatted with /** ... */ and generates HTML documentation.

Why this answer

The javadoc tool is specifically designed to parse Java source code and generate HTML documentation from specially formatted comments (/** ... */). It extracts the documentation comments and produces API documentation in HTML format, making option C correct.

Exam trap

Oracle often tests the distinction between the Java compiler (javac), the runtime launcher (java), and the documentation generator (javadoc), so the trap here is confusing the purpose of javac (compilation) with javadoc (documentation generation) because both operate on source code.

How to eliminate wrong answers

Option A is wrong because javac is the Java compiler, which translates .java source files into .class bytecode, not documentation. Option B is wrong because java is the Java application launcher that runs compiled bytecode, not a documentation generator. Option D is wrong because jar is the Java archiving tool used to package class files and resources into a single JAR file, not for generating documentation.

5
MCQeasy

Which statement about the Java compiler is true?

A.It translates Java source code into native machine code.
B.It produces executable files that run directly on the OS.
C.It executes Java programs.
D.It translates Java source code into bytecode.
AnswerD

javac produces .class files containing bytecode.

Why this answer

The Java compiler (javac) translates human-readable Java source code (.java files) into platform-independent bytecode (.class files). This bytecode is then executed by the Java Virtual Machine (JVM), not directly by the operating system. Option D correctly identifies this translation step.

Exam trap

The trap here is that candidates often confuse the Java compiler with a traditional compiler (like GCC) that produces native machine code, leading them to choose Option A, but the Java compiler's output is platform-independent bytecode, not native code.

How to eliminate wrong answers

Option A is wrong because the Java compiler does not translate source code into native machine code; that is the role of a just-in-time (JIT) compiler within the JVM at runtime. Option B is wrong because the Java compiler does not produce executable files that run directly on the OS; it produces .class files containing bytecode, which require the JVM to execute. Option C is wrong because the Java compiler does not execute programs; execution is performed by the JVM using the java command.

6
MCQmedium

Given the stack trace above, which line in MyClass.java caused the exception?

A.Line 30
B.Line 10
C.Line 15
D.Line 25
AnswerD

The stack trace indicates the exception at line 25 of MyClass.java.

Why this answer

The stack trace indicates that an exception occurred in MyClass.java at line 25, which is the line that calls a method that throws an unchecked exception (e.g., an ArithmeticException from division by zero or a NullPointerException). The stack trace shows the exact line number where the exception was thrown, and since the question states that line 25 is correct, that is the line in MyClass.java that caused the exception.

Exam trap

Oracle often tests the ability to read a stack trace and correctly identify the line number where the exception occurred, and the trap here is that candidates may confuse the line number in the stack trace with a line number from a different method or class, or they may misread the stack trace order and pick a line from a caller method instead of the actual throwing line.

How to eliminate wrong answers

Option A is wrong because line 30 is not mentioned in the stack trace as the source of the exception; the stack trace points to a different line number. Option B is wrong because line 10 is not the line where the exception was thrown; the stack trace shows the exception originated at a later line. Option C is wrong because line 15 is not indicated in the stack trace; the correct line number is 25, as per the stack trace output.

7
MCQhard

You are a Java developer working on an enterprise application that uses a modular architecture with Java Platform Module System (JPMS). The application consists of several modules: `com.app.core`, `com.app.util`, `com.app.service`, and `com.app.client`. The application runs on a server that has Java 17 installed. Recently, the operations team reported that after a deployment, the application fails to start with a `NoClassDefFoundError` for a class in `com.app.util`, even though the class exists in the compiled module. The deployment process uses a custom script that compiles the modules using `javac` with `--module-source-path`, then uses `jlink` to create a custom runtime image that includes only the required modules. The runtime image is then deployed to the server. The build logs show no errors during compilation or linking. However, on the server, the error occurs. The server has multiple versions of the same library on the classpath due to legacy scripts. You suspect that the error is due to a module resolution issue. Which corrective action should you take?

A.Recompile the application without using modules by placing all classes on the classpath instead.
B.Remove any classpath entries from the server startup script and rely exclusively on the module path provided by the runtime image.
C.Ensure that the module `com.app.util` exports the package containing the missing class in its module-info.java.
D.Add detailed logging in the module's initialization to trace the class loading and identify where the error originates.
AnswerB

The runtime image already contains all required modules; adding classpath can cause conflicting class definitions and the NoClassDefFoundError.

Why this answer

Option B is correct because the `NoClassDefFoundError` occurs when the custom runtime image built with `jlink` is deployed, but legacy scripts add classpath entries that cause module resolution conflicts. JPMS requires that all dependencies be on the module path; mixing classpath entries can lead to split packages or incorrect module resolution, resulting in the error. Removing classpath entries ensures the runtime image's module path is used exclusively, resolving the issue.

Exam trap

The trap here is that candidates often focus on module exports or compilation issues, but the real problem is the interference of classpath entries with JPMS module resolution, which is a subtle runtime behavior tested by Cisco.

How to eliminate wrong answers

Option A is wrong because recompiling without modules defeats the purpose of using JPMS and does not address the root cause of classpath interference; the error would likely persist due to legacy classpath entries. Option C is wrong because the error is a `NoClassDefFoundError` at runtime, not a compile-time accessibility issue; if the class exists in the module, the `exports` directive is likely already correct, and the problem is module resolution, not missing exports. Option D is wrong because adding logging only helps diagnose the issue but does not fix the underlying problem of classpath contamination; the corrective action must be to remove the conflicting classpath entries.

8
MCQmedium

A team is using a build tool to compile and package a Java application. They want to automatically run unit tests after compilation and before packaging. Which tool and configuration is most appropriate?

A.Jenkins pipeline with a stage for compile and test.
B.Ant with a target that depends on compile.
C.Gradle with a task that runs test after assemble.
D.Maven with lifecycle phases: test after compile.
AnswerD

Maven's 'test' phase runs after 'compile' and before 'package' by default.

Why this answer

Maven's lifecycle phases are ordered: compile, test, package. By placing 'test' after 'compile' in the lifecycle configuration, Maven automatically runs unit tests after compilation and before packaging. This is the most appropriate tool because Maven enforces a standard lifecycle, ensuring tests execute in the correct phase without custom scripting.

Exam trap

Oracle often tests the distinction between build tools (Maven, Gradle, Ant) and CI tools (Jenkins), trapping candidates who confuse a CI server's pipeline stages with a build tool's lifecycle phases.

How to eliminate wrong answers

Option A is wrong because Jenkins is a CI/CD automation server, not a build tool; it orchestrates builds but does not natively compile or package Java code. Option B is wrong because Ant requires explicit dependency declarations (e.g., a target that depends on compile) and does not have a built-in lifecycle; it is procedural, not declarative, making it less automatic. Option C is wrong because Gradle's 'assemble' task runs after 'test' in the default lifecycle; configuring a task to run 'test after assemble' would execute tests after packaging, not before.

9
MCQhard

You are a Java developer at a financial firm. The application processes transactions from a queue. The team recently migrated from Java 8 to Java 11. After the migration, the application intermittently throws an exception: 'java.lang.reflect.InaccessibleObjectException: Unable to make field private final byte[] java.lang.String.value accessible: module java.base does not 'opens java.lang' to unnamed module'. This error occurs when the application tries to use reflection to access private fields of String objects for serialization. The application runs on a server where you cannot modify the JVM startup scripts. However, you can modify the application code and the module-info.java file. You need to resolve the exception without breaking existing functionality. Which approach should you take?

A.Refactor the code to use public APIs instead of reflecting on String's internal fields.
B.Add --add-opens java.base/java.lang=ALL-UNNAMED to the JVM command line.
C.Use sun.misc.Unsafe to access the String field directly.
D.Add 'opens java.lang;' to the module-info.java file.
AnswerA

This avoids the module access issue entirely.

Why this answer

Option A is correct because the root cause is that the application uses reflection to access private fields of java.lang.String, which is prohibited in Java 9+ by default due to module system encapsulation. Refactoring to use public APIs (e.g., String.getBytes(), String.charAt()) eliminates the need for reflection entirely, resolving the InaccessibleObjectException without requiring JVM flags or module declarations, and preserves compatibility with Java 11.

Exam trap

Oracle often tests the misconception that you can fix module-access errors by adding 'opens' directives in your own module-info.java, but you cannot open packages belonging to other modules (like java.base) from your module descriptor.

How to eliminate wrong answers

Option B is wrong because it requires modifying JVM startup scripts to add --add-opens, which the problem explicitly states you cannot do. Option C is wrong because sun.misc.Unsafe is a dangerous, internal API that is deprecated for removal in future JDK versions and does not solve the module-access issue; it would still trigger similar encapsulation errors or be removed entirely. Option D is wrong because 'opens java.lang;' in module-info.java would attempt to open the java.lang package from the unnamed module, but the java.base module does not belong to your application's module, so you cannot open it from your module-info.java; only the owner module (java.base) can open its packages.

10
MCQeasy

A developer encounters a ClassNotFoundException at runtime. The class is present in the source code and compiles fine. Which is the most likely cause?

A.The class is in the wrong package.
B.The classpath does not include the directory or JAR containing the .class file.
C.The class is abstract.
D.The class has a static initializer that fails.
AnswerB

ClassNotFoundException occurs when the class definition is not found at runtime, usually due to incorrect classpath.

Why this answer

A ClassNotFoundException occurs when the Java Virtual Machine (JVM) cannot locate the .class file for a referenced class at runtime, even though the source code compiled successfully. Since the class compiles fine, the issue is not with the source code but with the runtime environment — specifically, the classpath does not include the directory or JAR file that contains the compiled .class file. The JVM uses the classpath to search for class files during class loading, and if the path is missing, it throws ClassNotFoundException.

Exam trap

The trap here is that candidates confuse a compile-time error (wrong package) with a runtime error (classpath issue), or they mistakenly think that a static initializer failure causes ClassNotFoundException instead of ExceptionInInitializerError.

How to eliminate wrong answers

Option A is wrong because a class in the wrong package would cause a compilation error (e.g., 'cannot find symbol'), not a runtime ClassNotFoundException after successful compilation. Option C is wrong because an abstract class can be loaded and used as a superclass or reference type without issue; abstractness does not prevent class loading. Option D is wrong because a static initializer that fails throws an ExceptionInInitializerError at runtime, not a ClassNotFoundException.

11
MCQmedium

What is the output if an ArithmeticException occurs in the try block and there is a finally block?

A.The exception is caught and handled by the finally block.
B.The finally block does not execute if an exception occurs.
C.The finally block executes, then the method throws the exception.
D.The method exits immediately without executing finally.
AnswerC

finally runs, then exception propagates.

Why this answer

Option C is correct because in Java, the `finally` block always executes after the `try` block, regardless of whether an exception occurs. If an `ArithmeticException` is thrown in the `try` block, the `finally` block runs first, and then the exception propagates up the call stack to be handled by an appropriate exception handler or the default handler.

Exam trap

Oracle often tests the misconception that the `finally` block only runs if no exception occurs, or that it can handle exceptions like a `catch` block, leading candidates to choose Option A or B.

How to eliminate wrong answers

Option A is wrong because the `finally` block is not designed to catch or handle exceptions; it is used for cleanup code (e.g., closing resources). Option B is wrong because the `finally` block executes even when an exception occurs, as per Java Language Specification §14.20.2. Option D is wrong because the method does not exit immediately; the `finally` block runs before the exception is propagated.

12
MCQeasy

A developer writes a method that reads a file and parses its contents. Which exception handling approach is best practice for ensuring the file is properly closed even if an exception occurs?

A.Use a throws clause and let the caller handle closing.
B.Use a try-catch block and close the resource in the catch block.
C.Use a try-with-resources statement.
D.Use a try-catch block and close the resource in the finally block.
AnswerC

Try-with-resources automatically closes resources that implement AutoCloseable, even if an exception occurs.

Why this answer

Option C is correct because the try-with-resources statement automatically closes any resource that implements AutoCloseable (such as FileReader or BufferedReader) at the end of the statement, regardless of whether an exception occurs. This eliminates the risk of resource leaks and is the recommended best practice in Java for handling resources that must be closed.

Exam trap

Cisco often tests the misconception that a finally block is the best practice for resource cleanup, but the trap here is that while a finally block works, try-with-resources is the modern, preferred approach that reduces boilerplate and eliminates common mistakes like forgetting to close in all paths.

How to eliminate wrong answers

Option A is wrong because using a throws clause shifts the responsibility of closing the file to the caller, which may forget to close it or may not have access to the resource reference, leading to resource leaks. Option B is wrong because closing the resource in the catch block only occurs if an exception is caught; if no exception occurs, the resource is never closed, causing a leak. Option D is wrong because while a finally block does ensure the resource is closed, it requires explicit null checks and manual close() calls, making the code more verbose and error-prone compared to the concise and automatic cleanup provided by try-with-resources.

13
MCQmedium

You are maintaining a multi-threaded banking application that processes transactions. In the `processTransaction` method, you have a try-catch block that catches `Exception` to handle any unexpected errors. Recently, the application intermittently fails to update account balances correctly due to unhandled exceptions. The logs show that sometimes a `RuntimeException` is thrown from a nested method, but it is not being logged or handled properly, leading to inconsistent state. The team wants to improve the exception handling to ensure that all exceptions are caught, logged, and the transaction is rolled back properly. The method currently uses a primitive try-catch-finally where the finally block commits the transaction if no exception occurred. Which approach best addresses the issue while maintaining clarity and correctness?

A.Remove the `catch (Exception e)` block and rely solely on the finally block to commit or roll back based on a boolean flag set in the try block.
B.Add a separate catch block for `RuntimeException` before the existing `catch (Exception e)` and call rollback there, then rethrow the exception.
C.Inside the try block, set a boolean success flag to true upon completion; in the finally block, check the flag: if false, rollback; if true, commit. Additionally, catch specific exceptions, log them, and ensure rollback logic is invoked.
D.Declare the method with `throws Exception` and let the caller handle the transaction rollback.
AnswerC

This pattern ensures that the transaction is only committed on success, and any exception triggers rollback. Logging can be done in the catch block or using a global exception handler.

Why this answer

Option C is correct: Use a try-catch block specifically for `RuntimeException` (and possibly other checked exceptions) to catch them, log, and roll back, then either rethrow or handle appropriately. The current catch of `Exception` is too broad and may be masking the fact that `RuntimeException` is not being logged because the catch block might not be executed if the exception occurs after the try block's scope? Actually, the issue is that the catch block may be catching but not properly rolling back. But more importantly, the method should not commit if any exception occurs; the finally block should only commit on success.

Option A is wrong because adding a separate `RuntimeException` catch before the generic `Exception` catch is syntactically possible but still commits in finally unless rollback is called. Option B is wrong because using a finally block to commit always commits even if an exception occurred, unless you use a flag. Option D is wrong because using `throws` is not a handling strategy; it pushes the problem to the caller without resolving the rollback requirement.

14
MCQhard

Refer to the exhibit. A Java source file fails to compile with the given error. What change should be made to fix the error?

A.Add a throws IOException clause to the enclosing method
B.Wrap the code in a try-catch for NullPointerException
C.Change the method to use a finally block
D.Import the java.io.IOException class
AnswerA

Declaring the exception allows it to propagate, fixing the compilation error.

Why this answer

The code is calling a method (e.g., `Files.readString()`, `BufferedReader.readLine()`, or similar) that throws a checked `IOException`. In Java, checked exceptions must be either caught with a try-catch block or declared in the enclosing method's `throws` clause. Option A adds the `throws IOException` declaration, which correctly propagates the exception to the caller, satisfying the compiler's requirement.

Exam trap

Oracle often tests the distinction between checked and unchecked exceptions, and the trap here is that candidates mistakenly think importing the class or using a `finally` block will resolve the compile-time error, when the actual fix is to either catch or declare the checked exception.

How to eliminate wrong answers

Option B is wrong because `NullPointerException` is an unchecked (runtime) exception and does not need to be declared or caught; the compiler error is about a checked exception, not a runtime one. Option C is wrong because a `finally` block is used for cleanup code (e.g., closing resources) and does not resolve the requirement to handle or declare a checked exception. Option D is wrong because `java.io.IOException` is already part of `java.lang` indirectly? Actually, `IOException` is in `java.io` and must be imported, but the error is not about an unknown class; the compiler error is specifically about an unhandled checked exception, not a missing import — the import alone does not fix the exception handling requirement.

15
MCQmedium

Consider the following code snippet: public int getValue() { try { return 1; } catch (Exception e) { return 2; } finally { return 3; } } What does the method return?

A.3
B.The code does not compile.
C.2
D.1
AnswerA

The finally block executes and its return statement takes precedence, returning 3.

Why this answer

The correct answer is A (3) because a `finally` block always executes after the `try` block, and if the `finally` block contains a `return` statement, that return value overrides any return value from the `try` or `catch` blocks. In Java, the `finally` block's `return` statement causes the method to exit with the value 3, regardless of what the `try` block attempted to return.

Exam trap

Oracle often tests the misconception that a `finally` block cannot override a `try` block's return value, or that the `finally` block runs after the method has already returned, leading candidates to incorrectly choose option D (1) or option C (2).

How to eliminate wrong answers

Option B is wrong because the code compiles successfully; the `finally` block is syntactically valid and the `try` block's `return` does not cause a compilation error. Option C is wrong because the `catch` block is never executed (no exception is thrown), and even if it were, the `finally` block's `return` would override it. Option D is wrong because although the `try` block executes `return 1`, the `finally` block's `return 3` executes immediately after, replacing the pending return value.

16
Multi-Selecthard

Which THREE statements about custom exceptions in Java are correct? (Select exactly 3)

Select 3 answers
A.A checked custom exception must be declared in the throws clause of any method that throws it.
B.A custom exception can be either checked or unchecked.
C.An unchecked custom exception must extend RuntimeException.
D.A custom exception class must directly extend Throwable.
E.A custom exception cannot have constructors that call super.
AnswersA, B, C

Checked exceptions must be either caught or declared.

Why this answer

Option A is correct because in Java, a checked custom exception (one that extends Exception but not RuntimeException) is a checked exception. The Java Language Specification (JLS) requires that any method which might throw a checked exception must either handle it with a try-catch block or declare it in its throws clause. This ensures the caller is aware of and can handle the exception, enforcing compile-time checking.

Exam trap

Cisco often tests the misconception that custom exceptions must directly extend Throwable or that they cannot have constructors calling super, when in fact they can extend any appropriate subclass and commonly do call super to set the message and cause.

17
Multi-Selecteasy

Which THREE of the following are checked exceptions in Java?

Select 3 answers
A.java.sql.SQLException
B.java.lang.NullPointerException
C.java.lang.ClassNotFoundException
D.java.lang.ArithmeticException
E.java.io.IOException
AnswersA, C, E

SQLException is a checked exception from JDBC operations.

Why this answer

Option A is correct because `java.sql.SQLException` is a checked exception in Java, meaning it must be either caught or declared in the method signature using `throws`. Checked exceptions are subclasses of `Exception` but not of `RuntimeException`, and `SQLException` directly extends `java.lang.Exception`, making it a checked exception that the compiler enforces handling for.

Exam trap

The trap here is that candidates often confuse runtime exceptions (like `NullPointerException` and `ArithmeticException`) with checked exceptions, because all are subclasses of `Throwable`, but only those that are not subclasses of `RuntimeException` or `Error` are checked.

18
MCQeasy

Refer to the exhibit. What does this warning indicate?

A.The -cp option is misspelled.
B.The destination directory bin does not exist.
C.The classpath is missing a required JAR file.
D.The source file has syntax errors.
AnswerC

The warning indicates that the classpath contains an invalid path, likely because the JAR file is not present.

Why this answer

The warning 'warning: [options] source value 8 is obsolete and will be removed in a future release' indicates that the Java compiler is using an older source version (1.8) which is deprecated. This warning is triggered when the -source or -release option is set to a value that is no longer supported in the current JDK. Option C is correct because the warning is about the classpath missing a required JAR file, which is a common cause of such deprecation warnings when the compiler cannot find dependencies and falls back to an older source level.

Exam trap

Oracle often tests the distinction between warnings and errors; the trap here is that candidates confuse a deprecation warning (which does not prevent compilation) with a syntax error or missing directory error, leading them to choose options that describe actual compilation failures.

How to eliminate wrong answers

Option A is wrong because the -cp option is not misspelled; the warning is about source version deprecation, not a typo in command-line options. Option B is wrong because the destination directory bin not existing would cause a different error ('error: directory not found: bin'), not a deprecation warning about source value. Option D is wrong because syntax errors in the source file would produce compilation errors (e.g., 'error: ';' expected'), not a warning about obsolete source value.

19
Multi-Selectmedium

Which TWO statements about the finally block are true? (Choose two.)

Select 2 answers
A.A try block must be followed by either a catch or finally.
B.The finally block executes only if an exception is thrown.
C.The finally block is used for resource cleanup.
D.The finally block cannot contain a return statement.
E.The finally block is executed after the catch block.
AnswersC, E

Finally is commonly used to close resources.

Why this answer

Option C is correct because the finally block is specifically designed for resource cleanup, such as closing file streams or database connections, ensuring that cleanup code runs regardless of whether an exception occurs. This is a fundamental use case in Java exception handling to prevent resource leaks.

Exam trap

The trap here is that candidates often think the finally block only runs when an exception occurs (Option B) or that it cannot contain a return statement (Option D), but the exam tests the precise behavior that finally always executes and can contain return statements, albeit with side effects.

20
Multi-Selecthard

Which TWO of the following development tools are specifically designed to analyze module dependencies or create custom runtime images?

Select 2 answers
A.jdeps
B.jlink
C.jar
D.javadoc
E.javac
AnswersA, B

jdeps analyzes class and module dependencies, helping to determine required modules.

Why this answer

The jdeps tool (option A) is a Java class dependency analyzer that examines class files or JARs to identify module-level dependencies, including transitive dependencies, and can suggest module dependencies for migration to the Java module system. The jlink tool (option B) is a Java linker that assembles and optimizes a set of modules and their dependencies into a custom runtime image, allowing you to create a minimal JRE tailored to your application.

Exam trap

Oracle often tests the distinction between tools that operate on source code (javac, javadoc) versus tools that operate on compiled artifacts and modules (jdeps, jlink), leading candidates to mistakenly associate 'dependency analysis' with the compiler or documentation generator.

21
MCQmedium

A method throws a checked exception. Which of the following is the correct way to handle it in the calling method?

A.Ignore the exception since it is checked.
B.Add a throws clause to the calling method.
C.Enclose the call in a try-catch block.
D.Use a finally block without catch.
AnswerC

Catching the exception handles it.

Why this answer

Option C is correct because checked exceptions must be handled by the calling method either by catching them with a try-catch block or by declaring them in a throws clause. Since the question asks for the correct way to handle it, enclosing the call in a try-catch block is a valid and direct handling approach that prevents the exception from propagating unhandled.

Exam trap

Oracle often tests the distinction between handling an exception (using try-catch) and deferring it (using throws), and the trap here is that candidates mistakenly think adding a throws clause is a form of handling, when in fact it only passes the responsibility up the call stack.

How to eliminate wrong answers

Option A is wrong because checked exceptions cannot be ignored; the Java compiler enforces that they are either caught or declared, and ignoring them results in a compilation error. Option B is wrong because adding a throws clause does not handle the exception—it merely delegates the responsibility to the caller, which is not handling but deferring. Option D is wrong because a finally block without a catch does not handle the exception; it only ensures cleanup code runs, but the checked exception remains unhandled and will cause a compilation error.

22
MCQeasy

Which command compiles a Java file and generates a .class file?

A.jar
B.javadoc
C.java
D.javac
AnswerD

javac compiles .java files to .class files.

Why this answer

The `javac` command is the Java compiler, which translates Java source code (`.java` files) into bytecode stored in `.class` files. This is the standard compilation step in the Java development process, as defined by the Java SE specification.

Exam trap

Oracle often tests the distinction between the compiler (`javac`) and the launcher (`java`), as candidates may confuse compiling with running a program, especially when both commands are used in sequence.

How to eliminate wrong answers

Option A is wrong because `jar` is the Java Archive tool used to package multiple `.class` files and resources into a single compressed archive (`.jar` file), not for compiling source code. Option B is wrong because `javadoc` generates API documentation from Java source code comments, producing HTML files, not `.class` files. Option C is wrong because `java` is the Java runtime launcher that executes compiled `.class` files (or `.jar` files) in the JVM, not a compiler.

23
MCQeasy

What does the java command with -jar option do?

A.Compiles Java files inside the JAR
B.Executes a JAR file by reading its manifest
C.Lists contents of the JAR file
D.Creates a new JAR file
AnswerB

java -jar runs the JAR with the class from manifest.

Why this answer

The `java -jar` command executes a JAR file by reading the `Main-Class` entry from the JAR's manifest file (`META-INF/MANIFEST.MF`). This tells the Java launcher which class contains the `public static void main(String[] args)` method to start the application. It does not compile, list, or create JAR files.

Exam trap

Oracle often tests the misconception that `java -jar` compiles or manipulates the JAR file, when in fact it strictly executes the application defined in the manifest.

How to eliminate wrong answers

Option A is wrong because the `java` command does not compile source files; compilation is done by the `javac` command, and the JAR file already contains compiled `.class` files. Option C is wrong because listing the contents of a JAR file is performed by the `jar tf` command, not by `java -jar`. Option D is wrong because creating a JAR file is done by the `jar cf` command, while `java -jar` only executes an existing JAR.

24
MCQhard

Refer to the exhibit. Which statement about this code is true?

A.The resource 'br' is not closed properly.
B.The code will not compile because of the throws clause.
C.The resource 'fis' is closed before 'br'.
D.The catch block is unnecessary.
AnswerD

The try-with-resources already ensures proper handling; the catch block just rethrows, making it redundant.

Why this answer

Option D is correct because the try-with-resources statement automatically closes both `FileInputStream` and `BufferedReader` in reverse order of their declaration, making an explicit catch block unnecessary for resource management. The code compiles and runs correctly without the catch block, as the resources are closed automatically regardless of whether an exception occurs.

Exam trap

Cisco often tests the misconception that a catch block is required in try-with-resources, but the catch block is optional and only needed if you want to handle exceptions locally rather than propagating them with `throws`.

How to eliminate wrong answers

Option A is wrong because the try-with-resources statement ensures that `br` is closed automatically at the end of the try block, even if an exception is thrown. Option B is wrong because the `throws` clause is valid and does not prevent compilation; it simply declares that the method may throw `IOException`. Option C is wrong because in a try-with-resources statement, resources are closed in the reverse order of their declaration, so `br` is closed before `fis`.

25
MCQmedium

A developer writes a method that reads a file and must ensure the file is closed even if an exception occurs. Which construct should be used?

A.A throws declaration in the method signature
B.A finally block without any resource declaration
C.A try-with-resources statement
D.A try-catch-finally block with explicit close in finally
AnswerC

try-with-resources automatically closes resources implementing AutoCloseable.

Why this answer

try-with-resources automatically closes resources that implement AutoCloseable, ensuring closure even if an exception occurs. Option D is correct. Option A (try-catch-finally without close) does not guarantee closure if exception occurs before close.

Option B (throws declaration) does not handle closure. Option C (finally block alone) requires explicit close, which might be missed.

26
MCQmedium

A developer writes a method that reads a file and processes its contents. If the file does not exist, the method should notify the caller. Which exception should the method declare in its throws clause?

A.RuntimeException
B.FileNotFoundException
C.Exception
D.IOException
AnswerB

FileNotFoundException is a checked exception specifically for missing files.

Why this answer

Option B is correct because `FileNotFoundException` is a checked exception that specifically indicates a file cannot be found at the specified path. The method must declare it in its `throws` clause to notify the caller that this condition can occur and must be handled or re-declared, as required by Java's checked exception rules.

Exam trap

Oracle often tests the distinction between checked and unchecked exceptions, and the trap here is that candidates choose `IOException` (Option D) because it is a parent class, failing to recognize that the most specific exception (`FileNotFoundException`) is the correct and precise choice for the given scenario.

How to eliminate wrong answers

Option A is wrong because `RuntimeException` is an unchecked exception; it does not need to be declared in a `throws` clause, and using it would not properly notify the caller of a checked file-not-found condition. Option C is wrong because `Exception` is too broad; declaring it would force the caller to handle or declare all checked exceptions, which is overly general and not specific to the file-not-found scenario. Option D is wrong because while `IOException` is a checked exception that could cover file-not-found, it is the parent class of `FileNotFoundException`; using the more specific `FileNotFoundException` is the correct practice to precisely communicate the exact failure condition.

27
Multi-Selecthard

Which THREE statements are true about the Java logging API (java.util.logging)?

Select 3 answers
A.Handlers can be attached to loggers to output messages
B.The default configuration logs all messages at FINEST level
C.Loggers are organized in a hierarchical namespace
D.All loggers automatically forward messages to the root logger
E.You can set severity levels per logger
AnswersA, C, E

Handlers define output destinations.

Why this answer

Option A is correct because the Java Logging API allows Handlers (such as ConsoleHandler, FileHandler, or custom handlers) to be attached to Logger objects to output log messages to destinations like the console, files, or network sockets. This is a core design pattern of the API: loggers produce log records, and handlers are responsible for publishing them.

Exam trap

Oracle often tests the misconception that the default logging level is FINEST or that all loggers automatically forward every message to the root logger, but in reality the default level is INFO and forwarding depends on level checks and the useParentHandlers flag.

28
Multi-Selectmedium

A developer is debugging a Java application that throws a NullPointerException. Which two actions help identify the source of the exception? (Choose two.)

Select 2 answers
A.Use System.out.println statements
B.Use a debugger to step through code
C.Examine the stack trace
D.Recompile with -g flag
E.Catch the exception and print its message
AnswersB, C

A debugger allows setting breakpoints and stepping through code to inspect variable values and find where the null reference occurs.

Why this answer

Examining the stack trace (option A) shows the exact line number where the exception occurred, and using a debugger (option D) allows stepping through code to see variable states. While System.out.println (B) and catching the exception (C) can be helpful, they are less efficient and don't provide the precise location as directly. Recompiling with -g (E) adds debug info but is not an action to identify the source; it's a prerequisite for better stack traces.

29
MCQmedium

You are responsible for deploying a Java desktop application that uses JavaFX and various third-party libraries. The application is modular and uses JPMS. To reduce the footprint and startup time, you decide to use jlink to create a custom runtime image that includes only the required modules. The application has a main module `com.myapp` that requires `javafx.controls`, `javafx.base`, and some other modules. After creating the runtime image using the command `jlink --module-path $JAVA_HOME/jmods:lib --add-modules com.myapp --output myapp-image`, you test the image on a development machine, and it works. However, when deploying to a customer's machine, the application fails to start with an error: "Error: Could not find or load main class com.myapp.Main". The customer's machine has no Java installed. The runtime image includes the `com.myapp` module. You verify that the `myapp-image/bin/java` launcher exists. The main class is correctly declared in the module-info.java of `com.myapp`. What is the most likely cause of this error?

A.Use the `--add-modules` option to include `javafx.controls` and other required modules in the command.
B.Use the `--launcher` option in jlink to create a launcher script that automatically runs the main class with the correct module.
C.Add the `--bind-services` option to jlink to automatically include service provider modules.
D.Ensure that the `com.myapp` module reads all required modules by adding `requires` directives in module-info.java.
AnswerB

The `--launcher` option generates a platform-specific script (e.g., myapp.sh or myapp.bat) that invokes the JVM with the correct module and main class, avoiding the need to specify them manually.

Why this answer

Option B is correct because the `jlink` tool does not automatically create a launcher script that specifies the main class for the runtime image. Without the `--launcher` option, the generated `java` launcher does not know which module and main class to execute, leading to the 'Could not find or load main class' error when no Java is installed on the customer's machine. Using `--launcher` creates a custom script (e.g., `myapp`) that invokes `java --module com.myapp/com.myapp.Main`, ensuring the correct entry point is used.

Exam trap

The trap here is that candidates assume the `java` launcher in the runtime image will automatically find the main class from the module descriptor, but in reality, without `--launcher`, the launcher requires explicit module and main class arguments, mimicking the standard `java` command behavior.

How to eliminate wrong answers

Option A is wrong because the `--add-modules` option is already used in the command to include `com.myapp` and its dependencies; the issue is not about missing modules but about the launcher not specifying the main class. Option C is wrong because `--bind-services` adds service provider modules automatically, which is unrelated to the main class resolution error; the error occurs because no launcher is configured to run the main class. Option D is wrong because the `requires` directives in `module-info.java` are already correctly declared (the app works on the dev machine), so the problem is not about missing module dependencies but about the runtime image lacking a launcher that specifies the main class.

30
Multi-Selectmedium

Which TWO are valid ways to handle a checked exception in a method?

Select 2 answers
A.Catch the exception within the method
B.Ignore the exception by doing nothing
C.Declare the exception in the throws clause
D.Use assert to suppress the exception
E.Convert it to a runtime exception by throwing a new RuntimeException
AnswersA, C

Catching is the primary way to handle.

Why this answer

Option A is correct because catching a checked exception within the method using a try-catch block is a valid way to handle it. The Java compiler enforces that checked exceptions (subclasses of Exception but not RuntimeException) must be either caught or declared, so catching the exception satisfies the compiler's requirement.

Exam trap

Oracle often tests the misconception that converting a checked exception to a RuntimeException (option E) is a valid way to handle it within the method, but the conversion itself requires the original exception to be caught or declared, so it is not a standalone handling mechanism.

31
MCQmedium

A developer tries to compile a modular Java application using the command shown in the exhibit. The compilation fails with the error shown. What is the most likely cause?

A.The `-d out` flag is incorrectly specified; it should point to the source directory.
B.The `-m` option should be `--module` instead.
C.The import statement should use the fully qualified class name instead of importing.
D.The `--module-source-path` does not include the location of the utility module.
AnswerD

The module source path must point to the directory that contains all module source directories; if missing, dependent modules cannot be resolved.

Why this answer

The error indicates that the compiler cannot find the utility module referenced in the `requires` directive. The `--module-source-path` option must list all directories containing module source code. Since the utility module's source is not included in the specified path, the compilation fails.

Option D correctly identifies this missing path as the cause.

Exam trap

Oracle often tests the distinction between module path and module source path, trapping candidates who confuse `-d` (output directory) with source path or who think import syntax is the issue when the real problem is a missing module source location.

How to eliminate wrong answers

Option A is wrong because `-d out` specifies the destination directory for compiled classes, not the source directory; it is correctly used here. Option B is wrong because `-m` is the correct short form for specifying the main module; `--module` is the long form but not required. Option C is wrong because the import statement is syntactically correct and does not cause a compilation error; the error is about a missing module, not about import resolution.

32
MCQhard

A developer is using try-with-resources with a custom resource class that implements AutoCloseable. The class's close() method throws a custom exception `ResourceException`. In the try block, an IOException occurs. Which of the following best describes the exception that is propagated to the caller?

A.The IOException is discarded and the ResourceException is thrown.
B.The IOException is propagated with the ResourceException added as a suppressed exception.
C.The IOException is lost and the caller receives no exception.
D.Both exceptions are thrown simultaneously as a multi-exception.
AnswerB

try-with-resources handles this by suppressing the close exception and propagating the primary exception.

Why this answer

When using try-with-resources, if both the try block and the close() method throw exceptions, the exception from the try block is the one propagated to the caller, and any exception from close() is added as a suppressed exception to that primary exception. This is specified in Java's try-with-resources semantics (JLS §14.20.3). Therefore, the IOException from the try block is propagated, and the ResourceException from close() is suppressed within it.

Exam trap

The trap here is that candidates often think the last exception thrown (from close()) overrides the earlier exception, but Java's try-with-resources specifically preserves the try block exception and suppresses the close() exception.

How to eliminate wrong answers

Option A is wrong because the IOException is not discarded; it is the primary exception propagated, and the ResourceException is added as a suppressed exception, not thrown instead. Option C is wrong because the IOException is not lost; it is propagated to the caller, and the caller receives the IOException with the ResourceException suppressed. Option D is wrong because Java does not throw multiple exceptions simultaneously; only one exception is propagated, and others are suppressed within it.

33
MCQhard

A team is designing a library that handles network timeouts. They create a custom exception `NetworkTimeoutException` that extends `Exception`. They want to ensure that callers are forced to handle this exception. Which declaration is appropriate for a method that throws this exception?

A.public void connect() throws RuntimeException
B.public void connect() throws NetworkTimeoutException
C.public void connect() throws e where e is NetworkTimeoutException
D.public void connect() throw NetworkTimeoutException
AnswerB

Correct syntax: checked exception declared with `throws` forces callers to handle or declare it.

Why this answer

Option B is correct because the method must declare the custom checked exception `NetworkTimeoutException` in its throws clause to force callers to handle it. Since `NetworkTimeoutException` extends `Exception` (not `RuntimeException`), it is a checked exception, and the Java compiler enforces that any method throwing it must declare it with the `throws` keyword followed by the exception type name.

Exam trap

The trap here is confusing the `throw` keyword (used to throw an exception in code) with the `throws` keyword (used in method declarations), and assuming that declaring a superclass like `RuntimeException` satisfies the requirement to declare a specific checked exception.

How to eliminate wrong answers

Option A is wrong because `RuntimeException` is an unchecked exception, so declaring it does not force callers to handle the custom checked exception; the method should declare `NetworkTimeoutException` specifically. Option C is wrong because the `throws` clause requires the exception class name directly, not a variable or placeholder like `e where e is NetworkTimeoutException`; Java syntax does not support such a construct. Option D is wrong because the keyword is `throws` (with an 's'), not `throw`; `throw` is used to actually throw an exception inside the method body, not in the method declaration.

34
MCQeasy

Which of the following exceptions is a checked exception?

A.ArrayIndexOutOfBoundsException
B.ArithmeticException
C.IOException
D.NullPointerException
AnswerC

IOException is a checked exception.

Why this answer

Option C is correct because IOException is a checked exception in Java, meaning it must be either caught or declared in the method signature using a try-catch block or throws clause. Checked exceptions are subclasses of Exception (excluding RuntimeException and its subclasses), and IOException directly extends Exception, making it subject to compile-time checking.

Exam trap

Oracle often tests the distinction between checked and unchecked exceptions by listing common RuntimeException subclasses (like NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException) as distractors, hoping candidates confuse them with checked exceptions due to their frequent occurrence in code.

How to eliminate wrong answers

Option A is wrong because ArrayIndexOutOfBoundsException is a subclass of RuntimeException, making it an unchecked exception that does not require explicit handling. Option B is wrong because ArithmeticException is also a subclass of RuntimeException, so it is unchecked and can occur at runtime without mandatory handling. Option D is wrong because NullPointerException is a subclass of RuntimeException, thus it is an unchecked exception that the compiler does not enforce handling for.

35
Multi-Selecthard

Which THREE are checked exceptions in Java? (Choose three.)

Select 3 answers
A.ArrayIndexOutOfBoundsException
B.SQLException
C.NullPointerException
D.IOException
E.FileNotFoundException
AnswersB, D, E

It is a checked exception.

Why this answer

SQLException is a checked exception in Java because it extends Exception directly (not RuntimeException). Checked exceptions must be either caught with a try-catch block or declared in the method signature using the throws clause. SQLException is thrown when there is a database access error or other SQL-related issues, forcing the developer to handle potential failures at compile time.

Exam trap

Oracle often tests the distinction between checked and unchecked exceptions by including common RuntimeException subclasses (like NullPointerException and ArrayIndexOutOfBoundsException) as distractors, exploiting the misconception that any exception must be handled.

36
MCQhard

Given the compilation error above, which fix would resolve the error?

A.Add a throws FileNotFoundException clause to the main method.
B.Change FileReader to BufferedReader.
C.Wrap the code in a try-catch block for FileNotFoundException.
D.Use FileInputStream instead.
AnswerC

Catching the exception handles it.

Why this answer

Option C is correct because the compilation error indicates that the code uses a constructor or method that throws a checked `FileNotFoundException` (a subclass of `IOException`). In Java, checked exceptions must be either caught with a try-catch block or declared in the method signature. Wrapping the code in a try-catch block for `FileNotFoundException` handles the exception locally, resolving the compilation error without altering the method signature.

Exam trap

The trap here is that candidates often think adding a `throws` clause (Option A) is always the correct fix, but the question's context (a compilation error within a method that may not be allowed to throw checked exceptions, such as the main method in a simple program) makes try-catch the appropriate solution, and they overlook that `FileInputStream` (Option D) also throws the same checked exception.

How to eliminate wrong answers

Option A is wrong because adding a `throws FileNotFoundException` clause to the main method would only propagate the exception, not resolve the compilation error if the error is due to an unhandled checked exception within the code; however, the question states the error is a compilation error, and while adding throws could fix it, the more standard and recommended fix for a single statement is to handle it locally with try-catch, and the question implies the error is from code that is not in a method that can throw it (e.g., inside a block without throws). Option B is wrong because changing `FileReader` to `BufferedReader` does not eliminate the `FileNotFoundException`; `BufferedReader` itself does not throw that exception, but it typically wraps a `FileReader` which does, so the underlying issue remains. Option D is wrong because using `FileInputStream` instead of `FileReader` still throws a `FileNotFoundException` (as both are checked exceptions), so it does not resolve the compilation error.

37
Multi-Selectmedium

Which TWO command-line tools are included in the Oracle JDK for monitoring and troubleshooting Java applications? (Select exactly 2)

Select 2 answers
A.jstack
B.jmod
C.jstat
D.javap
E.jdb
AnswersA, C

jstack prints Java thread dumps for troubleshooting deadlocks and thread issues.

Why this answer

jstack is a command-line tool included in the Oracle JDK that prints Java stack traces of threads for a given Java process or core dump. It is used to diagnose deadlocks, thread contention, and other concurrency issues by showing the state and call stack of each thread.

Exam trap

Oracle often tests the distinction between development tools (javap, jdb) and runtime monitoring tools (jstack, jstat), leading candidates to mistakenly select javap or jdb because they are familiar from debugging sessions.

38
MCQhard

A custom exception class must extend which class to be a checked exception?

A.Throwable
B.Error
C.RuntimeException
D.Exception
AnswerD

Any class that extends Exception (and not RuntimeException) is a checked exception.

Why this answer

Option D is correct because, in Java, a checked exception is any exception that is a subclass of `Exception` but not a subclass of `RuntimeException`. To create a custom checked exception, your class must extend `Exception` (or a subclass of `Exception` that is itself a checked exception). This forces callers to handle or declare the exception, enforcing compile-time checking.

Exam trap

The trap here is that candidates often confuse `Throwable` with `Exception` or think that extending `RuntimeException` still produces a checked exception, but the key distinction is that only subclasses of `Exception` (excluding `RuntimeException` and its subclasses) are checked.

How to eliminate wrong answers

Option A is wrong because `Throwable` is the superclass of all errors and exceptions; extending `Throwable` directly creates a class that is neither a checked exception nor an unchecked exception in the standard sense, and it is not the intended way to create a custom checked exception. Option B is wrong because `Error` is reserved for serious system-level problems (e.g., `OutOfMemoryError`) that are not meant to be caught or handled by application code; extending `Error` creates an unchecked, non-recoverable error, not a checked exception. Option C is wrong because `RuntimeException` is the base class for unchecked exceptions; extending `RuntimeException` creates an exception that does not require handling or declaration, which is the opposite of a checked exception.

39
Multi-Selectmedium

Which TWO of the following are best practices for exception handling in Java?

Select 2 answers
A.Catch specific exceptions rather than generic Exception or Throwable.
B.Always catch Exception in every method to prevent crashes.
C.Use try-with-resources for classes that implement AutoCloseable.
D.Throw an exception from a finally block to ensure cleanup failures are reported.
E.Ignore exceptions by leaving the catch block empty.
AnswersA, C

Specific exceptions allow precise handling and avoid catching unexpected errors.

Why this answer

Option A is correct because catching specific exceptions (e.g., IOException, SQLException) allows you to handle each error condition appropriately, rather than using a broad catch-all like Exception or Throwable which can mask unexpected bugs and make code harder to maintain. This follows the principle of precise exception handling, ensuring that only recoverable or expected exceptions are caught, while letting runtime exceptions propagate.

Exam trap

Oracle often tests the distinction between catching specific exceptions versus generic ones, and the trap here is that candidates may think catching Exception is a safe default, not realizing it hides important error details and violates best practices.

40
MCQmedium

When using try-with-resources, which interface must the resource implement?

A.Serializable
B.Runnable
C.AutoCloseable
D.Comparable
AnswerC

AutoCloseable (or its subinterface Closeable) is required for try-with-resources.

Why this answer

Option C is correct because the try-with-resources statement in Java requires that any resource declared in its parentheses implements the `AutoCloseable` interface (or its subinterface `Closeable`). This interface defines a single `close()` method, which the JVM automatically invokes at the end of the try block, ensuring proper resource management without needing an explicit `finally` block.

Exam trap

Oracle often tests the misconception that any interface with a single method (like `Runnable`) qualifies for try-with-resources, but the key requirement is that the interface must extend `AutoCloseable` and its `close()` method must be the one invoked for cleanup.

How to eliminate wrong answers

Option A is wrong because `Serializable` is a marker interface used for serializing object state to a byte stream, not for resource management. Option B is wrong because `Runnable` is a functional interface designed for thread execution via its `run()` method, not for closing resources. Option D is wrong because `Comparable` is used to define a natural ordering of objects via `compareTo()`, and has no connection to resource cleanup or the try-with-resources mechanism.

41
MCQmedium

Refer to the exhibit. Which action would best resolve this error without changing the code?

A.Compile with -Xlint to get more details.
B.Change the file path to a directory that exists.
C.Use a try-catch to handle FileNotFoundException.
D.Grant read permission on the file.
AnswerD

The error message explicitly says 'Permission denied', so adjusting permissions fixes the issue.

Why this answer

The error is a FileNotFoundException, which occurs when the file does not exist or cannot be opened. Since the code is correct and the file path is valid, the most likely cause is insufficient permissions. Granting read permission on the file resolves the issue without modifying the code, as it allows the JVM to access the file for reading.

Exam trap

Cisco often tests the distinction between handling an exception (try-catch) and resolving its root cause (e.g., permissions), leading candidates to choose the try-catch option even though it does not fix the underlying issue.

How to eliminate wrong answers

Option A is wrong because -Xlint provides warnings about code issues (e.g., unchecked casts), not runtime file access errors; it cannot fix a FileNotFoundException. Option B is wrong because the file path is already valid (the exhibit shows an existing directory), so changing it would not address a permission issue. Option C is wrong because using a try-catch would handle the exception at runtime but does not resolve the underlying cause (lack of read permission); the question asks for an action that resolves the error without changing the code, and adding a try-catch is a code change.

42
Drag & Dropmedium

Arrange the steps to use a for loop to iterate over an array in Java in the correct order.

Drag steps to the numbered slots on the right, or tap a step then tap a slot.

Steps
Order

Why this order

First set up the array, then write a for loop with proper syntax, access elements using index, execute body, and consider enhanced for.

43
Multi-Selectmedium

Which TWO statements are true about the finally block in exception handling? (Select exactly 2)

Select 2 answers
A.The finally block is executed only if an exception is thrown.
B.The finally block can be omitted only if the try block does not throw any checked exception.
C.The finally block is executed only if no exception is thrown.
D.The finally block is executed even if the try block contains a return statement.
E.The finally block is executed after the try block and any catch block, but before the method returns.
AnswersD, E

The finally block runs before the return value is passed back, ensuring cleanup.

Why this answer

Option D is correct because the finally block is always executed regardless of whether an exception is thrown or caught, and even if the try block contains a return statement. The Java Language Specification (JLS §14.20.2) guarantees that the finally block executes after the try block and any associated catch blocks, but before control is transferred to the caller, ensuring cleanup code runs.

Exam trap

Oracle often tests the misconception that the finally block is optional or conditional based on exception occurrence, but the trap here is that candidates forget the finally block executes even with a return statement in the try block, or they incorrectly think it only runs when no exception occurs.

44
MCQhard

Refer to the exhibit. A developer encounters this exception when running the application. The method divide is intended to handle division by zero. What is the most likely cause of the exception?

A.The divide method does not catch ArithmeticException.
B.The JVM is not configured to handle arithmetic exceptions.
C.The divide method uses integer division without checking the divisor.
D.The Main class does not declare throws ArithmeticException.
AnswerC

Integer division by zero throws ArithmeticException. The method should check if the divisor is zero before performing division.

Why this answer

The ArithmeticException is an unchecked exception thrown by the JVM when integer division by zero occurs. The stack trace points to line 12 in Calculator.java, which is inside the divide method. The most likely cause is that the divide method does not check if the divisor is zero before performing division.

Option A is incorrect because catching is not mandatory for unchecked exceptions. Option C is incorrect because unchecked exceptions do not need to be declared. Option D is incorrect because the JVM correctly throws the exception; it is not a configuration issue.

45
MCQmedium

A developer writes a method that reads a file and processes its contents. The method uses a BufferedReader wrapped around a FileReader. Which of the following approaches ensures that both resources are properly closed even if an exception occurs?

A.Close both resources in a finally block using separate try-catch for each close.
B.Use try-with-resources with both resources declared in the try header.
C.Close only the BufferedReader in a finally block.
D.Throw a custom exception after closing resources in the catch block.
AnswerB

try-with-resources ensures that each resource is closed automatically, in reverse order, even if an exception occurs.

Why this answer

Option B is correct because try-with-resources automatically closes resources declared in the try header in reverse order. Option A is wrong because closing only the outer resource may not close the inner one if wrapped incorrectly. Option C is wrong because closing in the finally block without checking for null can cause NullPointerException if resource creation fails.

Option D is wrong because throwing an exception before close statements prevents cleanup.

46
MCQhard

Given a method that catches Exception and then throws a RuntimeException, what is the effect?

A.The RuntimeException will not propagate if caught.
B.The method can throw RuntimeException without declaring it.
C.The method must declare throws RuntimeException.
D.The catch block cannot throw a RuntimeException because it is caught as Exception.
AnswerB

RuntimeException is unchecked, no throws required.

Why this answer

RuntimeException is unchecked, so it does not need to be declared. The method can throw it without a throws clause. Option A is correct.

47
Matchingmedium

Match each Java keyword to its use.

Drag a concept onto its matching description — or click a concept then click the description.

Concepts
Matches

Prevents modification: variable constant, method override, class inheritance

Belongs to the class rather than instances

Cannot be instantiated; used for classes and methods

Ensures mutual exclusion in multithreading

Marks field to be ignored during serialization

Why these pairings

Keywords have specific meanings in Java.

48
MCQhard

Given the following try-catch block: try { // some code } catch (IOException | NumberFormatException e) { e = new IOException("wrapper"); // throw e; } Which line causes a compilation error?

A.The multi-catch syntax
B.The assignment to e
C.No error
D.The throw statement
AnswerB

In a multi-catch clause, the exception parameter is implicitly final, so reassignment is not allowed.

Why this answer

In a multi-catch block, the exception parameter `e` is implicitly `final` and cannot be reassigned. The assignment `e = new IOException("wrapper")` violates this rule, causing a compilation error at that line.

Exam trap

The trap here is that candidates assume the multi-catch syntax itself is invalid or that the commented `throw` statement causes the error, overlooking the implicit `final` restriction on the exception parameter.

How to eliminate wrong answers

Option A is wrong because the multi-catch syntax `catch (IOException | NumberFormatException e)` is valid in Java 7+; it correctly catches both exception types. Option C is wrong because there is a compilation error due to the illegal assignment to `e`. Option D is wrong because the `throw e;` statement is commented out, so it does not cause an error; even if uncommented, the error would still be the assignment, not the throw.

49
MCQeasy

Which of the following is the best practice for resource management in Java?

A.Close resources in a finally block without null checks.
B.Rely on garbage collection to close resources.
C.Use try-with-resources statement.
D.Use a try-catch block and close resources in the catch block.
AnswerC

Try-with-resources automatically closes AutoCloseable resources.

Why this answer

Option C is correct because the try-with-resources statement (introduced in Java 7) automatically closes each resource declared in its header when the block exits, whether normally or due to an exception. This eliminates the need for explicit cleanup code and ensures that resources implementing `AutoCloseable` are closed reliably, preventing resource leaks.

Exam trap

Oracle often tests the misconception that garbage collection handles all resource cleanup, but the trap here is that candidates forget external resources (like I/O streams) are not managed by the garbage collector and require explicit closure via try-with-resources or finally blocks.

How to eliminate wrong answers

Option A is wrong because closing resources in a finally block without null checks can cause a `NullPointerException` if the resource variable is null, and it still requires verbose boilerplate code. Option B is wrong because garbage collection only reclaims memory, not external resources like file handles or database connections; relying on it can lead to resource exhaustion. Option D is wrong because closing resources in a catch block only executes if an exception occurs, leaving resources open if the try block completes normally, which defeats the purpose of guaranteed cleanup.

50
MCQeasy

You are a junior developer tasked with generating API documentation for a large Java project. The project uses Javadoc comments extensively, and you need to generate HTML documentation that includes all public and protected classes and methods. You have access to the source files in the `src` directory, and you want the output to be placed in a `docs` folder. Additionally, you want to include a custom header and footer in each generated page. The project uses multiple packages like `com.example.app`, `com.example.util`, and `com.example.data`. You plan to run the javadoc command from the project root. Which command should you use?

A.javadoc -d docs -header 'My App API' -footer 'Copyright 2024' -sourcepath src com.example.*
B.javadoc -d docs -private -sourcepath src com.example.app com.example.util com.example.data
C.javadoc -d docs -header 'My App API' -footer 'Copyright 2024' -sourcepath src com.example.app com.example.util com.example.data
D.javadoc -d docs -header 'My App API' -footer 'Copyright 2024' -sourcepath src -subpackages com.example
AnswerC

Correctly sets output, header, footer, sourcepath, and lists specific packages to document.

Why this answer

Option C is correct because it specifies the exact package names (`com.example.app`, `com.example.util`, `com.example.data`) that contain the public and protected classes and methods required for the documentation, uses `-d docs` to set the output directory, and includes `-header` and `-footer` to add custom header and footer text. This command generates HTML documentation for only the specified packages, meeting all requirements.

Exam trap

Oracle often tests the distinction between `-subpackages` and explicitly listing packages, where candidates mistakenly choose `-subpackages` thinking it is more efficient, but it may include unwanted packages and does not match the requirement to document only the three specified packages.

How to eliminate wrong answers

Option A is wrong because `com.example.*` is not a valid package name for the `javadoc` command; it would be interpreted as a literal package name with an asterisk, causing the tool to fail to find any classes. Option B is wrong because it uses `-private` which includes private members, but the requirement is to include only public and protected classes and methods, and it omits the `-header` and `-footer` options. Option D is wrong because `-subpackages com.example` recursively includes all subpackages (e.g., `com.example.internal`), which may include packages not intended for documentation, and it does not restrict to the three specified packages.

51
MCQeasy

Which command is used to run a Java application from the command line?

A.jar
B.javac
C.java
D.javadoc
AnswerC

java runs the JVM.

Why this answer

The `java` command is the correct tool to launch a Java application from the command line. It invokes the Java Virtual Machine (JVM) to load and execute the compiled bytecode contained in `.class` files or a JAR file. Without this command, the application cannot run.

Exam trap

Oracle often tests the distinction between compilation (`javac`) and execution (`java`), trapping candidates who confuse the compiler with the runtime launcher.

How to eliminate wrong answers

Option A is wrong because `jar` is used to create, view, or extract Java Archive (JAR) files, not to run applications. Option B is wrong because `javac` is the Java compiler that translates `.java` source files into `.class` bytecode, but it does not execute them. Option D is wrong because `javadoc` generates API documentation from Java source code comments, not run applications.

52
MCQhard

Consider a Java application that throws a NullPointerException deep inside a library method. The stack trace does not include the caller's line numbers because the library was compiled without debug information. Which approach would best help identify the root cause?

A.Use a debugger to set breakpoints in the library.
B.Recompile the library with -g flag and redeploy.
C.Use logging statements in the application code before and after the call.
D.Add a try-catch around the library call and print the stack trace.
AnswerB

The -g flag generates debugging information including line numbers, making stack traces more informative.

Why this answer

Option B is correct because recompiling the library with the `-g` flag includes debug information (such as line numbers and local variable names) in the class files. This allows the JVM to produce a stack trace with precise line numbers, enabling you to trace the NullPointerException back to the exact source line in the library code, even though the library was originally compiled without debug info.

Exam trap

Oracle often tests the misconception that adding a try-catch or logging around the call site can reveal the internal cause of an exception, when in fact only the library's own debug information (or recompilation with `-g`) can provide the line-level detail needed to trace the root cause.

How to eliminate wrong answers

Option A is wrong because setting breakpoints in the library requires the library to have been compiled with debug information; without it, the debugger cannot map bytecode to source lines, making breakpoints ineffective. Option C is wrong because adding logging statements in the application code only shows when the call is made and returns, but does not reveal where inside the library the NullPointerException occurs, so the root cause remains hidden. Option D is wrong because adding a try-catch around the library call and printing the stack trace will only show the same incomplete stack trace (without line numbers) that was already available; it does not add the missing debug information needed to pinpoint the exact location.

53
MCQeasy

A developer is maintaining a Java backend service for order processing. The service uses a third-party library that throws a checked PaymentException when a payment fails. The current processOrder method catches Exception generically, logs the error, and returns null. The business requires that when a payment fails, the order status must be updated to 'FAILED' in the database, and a notification must be sent to the customer. However, due to the generic catch, these actions are not performed. The developer must modify the code to meet the business requirements without changing the external API of the class (i.e., the method signature must remain the same and must not throw any exceptions to the caller). Which course of action should the developer take?

A.Catch PaymentException specifically, update the order status and send notification, then throw a new RuntimeException to indicate failure.
B.Remove the try-catch block and declare the method with throws Exception, allowing the caller to handle payment failures.
C.Use a finally block to update the order status and send notification regardless of success or failure.
D.In the catch block, check if the exception is an instance of PaymentException, then update the order status and send notification. Do not rethrow the exception.
AnswerD

This handles the specific exception, performs required actions, and does not propagate any exception, meeting all requirements.

Why this answer

The best course is to catch PaymentException specifically, perform the required business logic (update order status and send notification), and then either not rethrow the exception or rethrow it as an unchecked exception if needed. However, the requirement says 'must not throw any exceptions to the caller', so the method should not propagate any exception. Option A catches PaymentException, handles the business logic, and then rethrows a RuntimeException, which would propagate to the caller, violating the requirement.

Option B removes exception handling, causing checked Exception to be thrown, which also propagates. Option D uses a finally block, which would execute even on success, leading to incorrect notifications. Option C catches Exception, checks if it is PaymentException, handles the business logic, and then does not rethrow the exception, ensuring the method completes normally.

This satisfies the requirement while handling the specific exception.

54
MCQeasy

A developer needs to handle a specific checked exception, FileNotFoundException, but also wants to catch any other IOException that might occur. Which catch block ordering is correct?

A.Use a multi-catch: catch (FileNotFoundException | IOException e).
B.catch (IOException e) first, then catch (FileNotFoundException e).
C.catch (FileNotFoundException e) first, then catch (IOException e).
D.Use a single catch (Exception e).
AnswerC

This is correct because the more specific exception must be caught before the more general one.

Why this answer

Option C is correct because checked exceptions must be caught in order from most specific to most general. FileNotFoundException is a subclass of IOException, so it must be caught first; otherwise, the more specific catch block would be unreachable and cause a compilation error. This ordering ensures that the developer can handle the specific FileNotFoundException separately while still catching any other IOException in the second block.

Exam trap

The trap here is that candidates often think multi-catch can combine any exception types, but the compiler forbids combining a parent and child exception in the same multi-catch clause, and also forbids catching a parent before a child in separate catch blocks.

How to eliminate wrong answers

Option A is wrong because a multi-catch clause cannot contain exception types that are in a parent-child relationship; 'catch (FileNotFoundException | IOException e)' would cause a compilation error since FileNotFoundException is a subclass of IOException. Option B is wrong because catching IOException first makes the subsequent catch for FileNotFoundException unreachable, leading to a compilation error. Option D is wrong because catching Exception is too broad and would catch all exceptions, including unchecked ones like NullPointerException, which defeats the purpose of specifically handling FileNotFoundException and other IOExceptions.

55
MCQmedium

Refer to the exhibit. A Java program throws a NullPointerException. Which is the most likely cause?

A.An object not initialized before use
B.A syntax error in the try block
C.Incorrect classpath preventing class loading
D.A missing import statement in the source code
AnswerA

NullPointerException occurs when invoking a method or field on a null reference.

Why this answer

A NullPointerException is thrown when the JVM attempts to access a method or field on an object reference that is null. The most common cause is that the object was declared but never instantiated (e.g., `String s; s.length();`). This is a runtime exception, not a compile-time error, so it occurs during execution when the reference variable points to null.

Exam trap

Oracle often tests the distinction between compile-time errors (syntax, imports, classpath) and runtime exceptions (NullPointerException), trapping candidates who confuse a missing import or classpath issue with a null reference problem.

How to eliminate wrong answers

Option B is wrong because a syntax error in the try block would be caught at compile time, not at runtime as a NullPointerException. Option C is wrong because an incorrect classpath prevents class loading, resulting in a ClassNotFoundException or NoClassDefFoundError, not a NullPointerException. Option D is wrong because a missing import statement causes a compile-time error (e.g., 'cannot find symbol'), not a runtime NullPointerException.

56
MCQeasy

A developer compiles a Java application using the command `javac -d bin src/com/example/App.java`. Which of the following is true?

A.The compiler searches for source files in the `bin` directory.
B.The compiled .class files are placed in the `bin` directory maintaining the package structure.
C.The compiler creates a JAR file named `App.jar` in the `bin` directory.
D.The compiler compiles the code into a named module.
AnswerB

`-d bin` sets the root for output; the class file will be at `bin/com/example/App.class`.

Why this answer

The `-d` option in the `javac` command specifies the destination directory for compiled `.class` files. When `-d bin` is used, the compiler places the `.class` files into the `bin` directory, preserving the package directory structure (e.g., `bin/com/example/App.class`). This is the standard behavior for organizing compiled output separately from source code.

Exam trap

Oracle often tests the misconception that `-d` specifies the source directory or that `javac` can produce JAR files, leading candidates to confuse the roles of `javac` and `jar` tools.

How to eliminate wrong answers

Option A is wrong because the `-d` flag specifies the output directory, not the source directory; the compiler searches for source files in the path provided after the `-d` option (here, `src/com/example/App.java`), not in `bin`. Option C is wrong because `javac` does not create JAR files; JAR creation is done with the `jar` tool, not the `javac` compiler. Option D is wrong because the command does not include any module-related options (like `--module-source-path` or `-p`) and compiles a single class file, not a named module; named modules require a `module-info.java` file and specific module path settings.

57
MCQhard

A developer encounters an ArrayIndexOutOfBoundsException while running a unit test. The stack trace shows the error occurs in a method that is called from many places. Which tool or technique would most efficiently identify the specific call path?

A.Review the code manually to trace all possible callers.
B.Set a breakpoint in the method and debug the test.
C.Run a static analysis tool to detect the issue.
D.Add log statements at the beginning of the method.
AnswerB

Debugging allows inspection of the call stack and variables.

Why this answer

Setting a breakpoint in the method and debugging the test allows the developer to inspect the call stack at runtime, immediately revealing the exact sequence of method invocations that led to the ArrayIndexOutOfBoundsException. This is the most efficient approach because it directly captures the specific call path without requiring manual tracing or post-hoc analysis.

Exam trap

Oracle often tests the misconception that static analysis tools can identify runtime call paths, but they only detect potential code issues, not the specific execution flow that leads to an exception.

How to eliminate wrong answers

Option A is wrong because manually reviewing all possible callers is time-consuming and error-prone, especially in a large codebase where the method is called from many places, and it does not guarantee identifying the exact runtime path that triggers the exception. Option C is wrong because static analysis tools can detect potential array index issues but cannot determine the specific runtime call path that leads to the exception, as they analyze code without execution context. Option D is wrong because adding log statements requires modifying code, recompiling, and re-running the test, which is less efficient than debugging and may not capture the exact state at the point of failure without extensive logging.

58
MCQeasy

A developer writes a catch block that handles multiple exception types that have a subclass relationship. Which of the following is a valid use of the multi-catch feature?

A.catch (IOException | FileNotFoundException e) { ... }
B.catch (IOException e) { ... } catch (SomeOtherUnrelatedException e) { ... }
C.catch (FileNotFoundException | IOException e) { ... }
D.catch (IOException e) { ... } catch (FileNotFoundException e) { ... }
AnswerB

Separate catches are allowed; the more specific exception (if needed) should come first, but if they are unrelated, order doesn't matter. This approach is valid.

Why this answer

Option B is correct because it demonstrates the proper use of separate catch blocks for unrelated exception types, which is valid. The multi-catch feature (introduced in Java 7) allows catching multiple exception types in a single catch block only if they are not in a parent-child relationship; otherwise, the compiler reports an error due to unreachable code. Since IOException and SomeOtherUnrelatedException are unrelated, separate catch blocks are perfectly valid.

Exam trap

Cisco often tests the rule that multi-catch cannot contain exception types with a subclass relationship, and that separate catch blocks must order exceptions from most specific to most general to avoid unreachable code.

How to eliminate wrong answers

Option A is wrong because it attempts to catch IOException and FileNotFoundException in a multi-catch block, but FileNotFoundException is a subclass of IOException, making the catch for FileNotFoundException unreachable and causing a compilation error. Option C is wrong for the same reason as A — the order does not matter; the compiler still detects the subclass relationship and rejects the multi-catch. Option D is wrong because it places the more specific exception (FileNotFoundException) after the more general one (IOException), which means the FileNotFoundException catch block will never be executed (unreachable code), leading to a compilation error.

59
MCQhard

A team is developing a Java application that uses many third-party libraries. One library throws a checked exception that is not declared in its method signature. Which approach best handles this situation?

A.Ignore the exception because it is not declared.
B.Declare the library's exception in the method signature.
C.Wrap the exception in a RuntimeException and throw it.
D.Catch the exception and log it, then continue execution.
AnswerC

This satisfies the compiler and preserves the exception chain.

Why this answer

Option C is correct because a checked exception that is not declared in a method signature cannot be propagated without handling it. Wrapping it in a RuntimeException (an unchecked exception) bypasses the compiler's checked-exception enforcement, allowing the exception to be thrown without modifying the method signature. This is a common pattern when integrating third-party libraries that throw checked exceptions from methods that do not declare them.

Exam trap

The trap here is that candidates may think they can simply declare the library's exception in their own method signature (Option B), but the compiler requires the exception to be actually declared in the library's method signature, which it is not, making this approach invalid.

How to eliminate wrong answers

Option A is wrong because ignoring a checked exception that is not declared in the method signature will cause a compilation error; the compiler enforces that checked exceptions must be either caught or declared. Option B is wrong because you cannot declare an exception in your method signature that the library method does not declare; the compiler will not allow you to declare an exception that is not actually thrown by the called method. Option D is wrong because catching and logging the exception then continuing execution may mask critical failures, and it does not address the fact that the exception is not declared in the method signature, which still prevents compilation.

60
Multi-Selectmedium

Which TWO are benefits of using try-with-resources?

Select 2 answers
A.It ensures resources are closed even if an exception occurs
B.It eliminates the need for finally block entirely
C.Resources are closed automatically only if no exception occurs
D.Resources are closed in reverse order of declaration
E.It requires that resources implement the Closeable interface
AnswersA, D

Yes, closure happens automatically on any exit.

Why this answer

Option A is correct because the try-with-resources statement ensures that each resource declared in the try clause is automatically closed at the end of the statement, regardless of whether an exception occurs. This is achieved by the Java compiler generating implicit finally blocks that call the close() method on each resource, even if an exception is thrown during the try block or during the closing of another resource.

Exam trap

Oracle often tests the distinction between AutoCloseable and Closeable, and the misconception that resources are only closed if no exception occurs, leading candidates to incorrectly select Option C or E.

61
MCQeasy

Refer to the exhibit. Which statement is true about the InvalidInputException class?

A.It cannot be thrown by a method.
B.It is a checked exception.
C.It is an unchecked exception.
D.It can only be caught in a finally block.
AnswerB

Extending Exception (not RuntimeException) creates a checked exception.

Why this answer

The InvalidInputException class extends Exception, which makes it a checked exception. Checked exceptions must be either caught or declared in the method signature using 'throws', otherwise the code will not compile. This is the core reason why option B is correct.

Exam trap

Oracle often tests whether candidates confuse checked and unchecked exceptions by presenting a custom exception class that extends Exception (checked) but looks like it might be unchecked because of its name or usage context.

How to eliminate wrong answers

Option A is wrong because a checked exception like InvalidInputException can be thrown by a method using the 'throw' statement, as long as the method declares it with 'throws'. Option C is wrong because InvalidInputException extends Exception, not RuntimeException, so it is a checked exception, not an unchecked exception. Option D is wrong because a checked exception can be caught in a try block or propagated, not only in a finally block; the finally block is for cleanup code and does not catch exceptions by itself.

Ready to test yourself?

Try a timed practice session using only Exceptions Tools questions.