Explore easy questions on exception handling in Java, including checked vs. unchecked exceptions, keywords, and key rules for structuring try/catch blocks.
What happens when an error occurs within a method in Java?
Explanation: When an error occurs, an exception object containing error details is created and given to the runtime system. The program does not immediately shut down, and warnings may not appear at compile time for exceptions. Ignoring errors is incorrect, as exceptions signal issues needing attention.
Why would you use a try/catch block in Java programming?
Explanation: A try/catch block indicates awareness and preparation for handling exceptions. It does not directly prevent method calls, make code faster, or comment out sections. Its primary use is structured error handling.
Which type of exception does the Java compiler check during compilation?
Explanation: Checked exceptions are verified during compilation to ensure the programmer handles them. Unchecked exceptions are not checked by the compiler, and syntax or logic errors are not considered exception types.
Which of the following is an example of an unchecked exception in Java?
Explanation: NullPointerException is an unchecked exception, not checked at compile time. The other options are checked exceptions that require handling by the programmer.
Which keyword in Java is used to throw an exception object?
Explanation: The 'throw' keyword creates and passes an exception to the runtime system. 'throws' declares but does not throw an exception, 'catch' is for handling, and 'raise' is not a Java keyword.
Which Java class is the direct superclass of all exception classes?
Explanation: All exception classes directly or indirectly extend the Throwable class. Exception is a subclass of Throwable. RuntimeException and Error are further subclasses, not the top-most superclass.
Which statement about try/catch/finally structure in Java is true?
Explanation: A catch or finally block must follow a try block, making the first statement correct. You cannot insert code between try and catch, and a try block must have either catch or finally, though not necessarily both. Using all three at once is not mandatory.
What characterizes an unchecked exception in Java?
Explanation: Unchecked exceptions are not verified by the compiler and do not require explicit handling or declaration. They can still be caught, and they're not always fatal, nor must they be declared using 'throws'.