SlideShare a Scribd company logo
OCP Java SE 8 Exam
Sample Questions
Exceptions and Assertions
Hari Kiran & S G Ganesh
Question
Consider the following program:
class ChainedException {
public static void foo() {
try {
throw new ArrayIndexOutOfBoundsException();
} catch(ArrayIndexOutOfBoundsException oob) {
RuntimeException re = new RuntimeException(oob);
re.initCause(oob);
throw re;
}
}
public static void main(String []args) {
try {
foo();
} catch(Exception re) {
System.out.println(re.getClass());
} } }
https://ocpjava.wordpress.com
When executed this program from
main() by calling foo() method,
prints which of the following?
A. class
java.lang.RuntimeException
B. class
java.lang.IllegalStateException
C. class java.lang.Exception
D. class
java.lang.ArrayIndexOutOfBou
ndsException
Answer
Consider the following program:
class ChainedException {
public static void foo() {
try {
throw new ArrayIndexOutOfBoundsException();
} catch(ArrayIndexOutOfBoundsException oob) {
RuntimeException re = new RuntimeException(oob);
re.initCause(oob);
throw re;
}
}
public static void main(String []args) {
try {
foo();
} catch(Exception re) {
System.out.println(re.getClass());
} } }
https://ocpjava.wordpress.com
When executed this program from
main() by calling foo() method,
prints which of the following?
A. class
java.lang.RuntimeException
B. class
java.lang.IllegalStateException
C. class java.lang.Exception
D. class
java.lang.ArrayIndexOutOfBoun
dsException
Explanation
B. class java.lang.IllegalStateException
In the expression new RuntimeException(oob);, the
exception object oob is already chained to the
RuntimeException object. The method initCause() cannot be
called on an exception object that already has an exception
object chained during the constructor call.
Hence, the call re.initCause(oob); results in initCause()
throwing an IllegalStateException .
https://ocpjava.wordpress.com
Question
Consider the following program:
class EHBehavior {
public static void main(String []args) {
try {
int i = 10/0; // LINE A
System.out.print("after throw -> ");
} catch(ArithmeticException ae) {
System.out.print("in catch -> ");
return;
} finally {
System.out.print("in finally -> ");
}
System.out.print("after everything");
} }
Which one of the following options best describes the behaviour of this program?
A. The program prints the following: in catch -> in finally -> after everything
B. The program prints the following: after throw -> in catch -> in finally -> after
everything
C. The program prints the following: in catch -> after everything
D. The program prints the following: in catch -> in finally ->
https://ocpjava.wordpress.com
Answer
Consider the following program:
class EHBehavior {
public static void main(String []args) {
try {
int i = 10/0; // LINE A
System.out.print("after throw -> ");
} catch(ArithmeticException ae) {
System.out.print("in catch -> ");
return;
} finally {
System.out.print("in finally -> ");
}
System.out.print("after everything");
} }
Which one of the following options best describes the behaviour of this program?
A. The program prints the following: in catch -> in finally -> after everything
B. The program prints the following: after throw -> in catch -> in finally -> after
everything
C. The program prints the following: in catch -> after everything
D. The program prints the following: in catch -> in finally ->
https://ocpjava.wordpress.com
Explanation
D . The program prints the following: in catch -> in finally ->
The statement println("after throw -> "); will never be
executed since the line marked with the comment LINE A
throws an exception. The catch handles ArithmeticException ,
so println("in catch -> "); will be executed.
Following that, there is a return statement, so the function
returns. But before the function returns, the finally statement
should be called, hence the statement println("in finally -> ");
will get executed. So, the statement println("after
everything"); will never get executed
https://ocpjava.wordpress.com
Question
Consider the following program:
import java.util.Scanner;
class AutoCloseableTest {
public static void main(String []args) {
try (Scanner consoleScanner = new Scanner(System.in)) {
consoleScanner.close(); // CLOSE
consoleScanner.close();
}
}
}
Which one of the following statements is correct?
A. This program terminates normally without throwing any exceptions
B. This program throws an IllegalStateException
C. This program throws an IOException
D. This program throws an AlreadyClosedException
https://ocpjava.wordpress.com
Answer
Consider the following program:
import java.util.Scanner;
class AutoCloseableTest {
public static void main(String []args) {
try (Scanner consoleScanner = new Scanner(System.in)) {
consoleScanner.close(); // CLOSE
consoleScanner.close();
}
}
}
Which one of the following statements is correct?
A. This program terminates normally without throwing any exceptions
B. This program throws an IllegalStateException
C. This program throws an IOException
D. This program throws an AlreadyClosedException
https://ocpjava.wordpress.com
Explanation
A . This program terminates normally without throwing any
exceptions
The try-with-resources statement internally expands to call
the close() method in the finally block. If the resource is
explicitly closed in the try block, then calling close()
again does not have any effect. From the description of the
close() method in the AutoCloseable interface: “Closes this
stream and releases any system resources associated with it.
If the stream is already closed, then invoking this method has
no effect.”
https://ocpjava.wordpress.com
Question
Consider the following program:
class AssertionFailure {
public static void main(String []args) {
try {
assert false;
} catch(RuntimeException re) {
System.out.println("RuntimeException");
} catch(Exception e) {
System.out.println("Exception");
} catch(Error e) { // LINE A
System.out.println("Error" + e);
} catch(Throwable t) {
System.out.println("Throwable");
}
}
}
https://ocpjava.wordpress.com
This program is invoked from the
command line as follows:
java AssertionFailure
Choose one of the following options
describes the behaviour of this
program:
A. Prints "RuntimeException" in
console
B. Prints "Exception"
C. Prints "Error"
D. Prints "Throwable"
E. Does not print any output on
console
Answer
Consider the following program:
class AssertionFailure {
public static void main(String []args) {
try {
assert false;
} catch(RuntimeException re) {
System.out.println("RuntimeException");
} catch(Exception e) {
System.out.println("Exception");
} catch(Error e) { // LINE A
System.out.println("Error" + e);
} catch(Throwable t) {
System.out.println("Throwable");
}
}
}
https://ocpjava.wordpress.com
This program is invoked from the
command line as follows:
java AssertionFailure
Choose one of the following options
describes the behaviour of this
program:
A. Prints "RuntimeException" in
console
B. Prints "Exception"
C. Prints "Error"
D. Prints "Throwable"
E. Does not print any output on
console
Explanation
E . Does not print any output on the console
By default, assertions are disabled. If -ea (or the -
enableassertions option to enable assertions), then the
program would have printed "Error" since the exception
thrown in the case of assertion failure is
java.lang.AssertionError , which is derived from
the Error class
https://ocpjava.wordpress.com
Question
Consider the following class hierarchy from the package
javax.security.auth.login and answer the questions.
Which of the following handlers that makes use of multi-catch exception handler
feature will compile without errors?
A. catch (AccountException | LoginException exception)
B. catch (AccountException | AccountExpiredException exception)
C. catch (AccountExpiredException | AccountNotFoundException exception)
D. catch (AccountExpiredException exception1 | AccountNotFoundException
exception2)
https://ocpjava.wordpress.com
Answer
Consider the following class hierarchy from the package
javax.security.auth.login and answer the questions.
Which of the following handlers that makes use of multi-catch exception handler
feature will compile without errors?
A. catch (AccountException | LoginException exception)
B. catch (AccountException | AccountExpiredException exception)
C. catch (AccountExpiredException | AccountNotFoundException exception)
D. catch (AccountExpiredException exception1 | AccountNotFoundException
exception2)
https://ocpjava.wordpress.com
Explanation
C . catch (A ccountExpiredException | A
ccountNotFoundException exception)
For A and B, the base type handler is provided with the
derived type handler, hence the multi-catch is incorrect.
For D, the exception name exception1 is redundant and will
result in a syntax error. C is the correct option and this will
compile fine without errors.
https://ocpjava.wordpress.com
• Check out our latest book for
OCPJP 8 exam preparation
• http://amzn.to/1NNtho2
• www.apress.com/9781484218358
(download source code here)
• https://ocpjava.wordpress.com
(more ocpjp 8 resources here)
http://facebook.com/ocpjava

More Related Content

What's hot

End to end testing - strategies
End to end testing - strategiesEnd to end testing - strategies
End to end testing - strategies
anuvip
 
Automated Testing vs Manual Testing
Automated Testing vs Manual TestingAutomated Testing vs Manual Testing
Automated Testing vs Manual Testing
Directi Group
 
Automation testing
Automation testingAutomation testing
Automation testing
Biswajit Pratihari
 
Test Automation Frameworks: Assumptions, Concepts & Tools
Test Automation Frameworks: Assumptions, Concepts & ToolsTest Automation Frameworks: Assumptions, Concepts & Tools
Test Automation Frameworks: Assumptions, Concepts & Tools
Amit Rawat
 
Oracle APEX Social Login
Oracle APEX Social LoginOracle APEX Social Login
Oracle APEX Social Login
msewtz
 
Data Driven Framework in Selenium
Data Driven Framework in SeleniumData Driven Framework in Selenium
Data Driven Framework in Selenium
Knoldus Inc.
 
Integration testing for microservices with Spring Boot
Integration testing for microservices with Spring BootIntegration testing for microservices with Spring Boot
Integration testing for microservices with Spring Boot
Oleksandr Romanov
 
Automation - web testing with selenium
Automation - web testing with seleniumAutomation - web testing with selenium
Automation - web testing with selenium
Tzirla Rozental
 
Unit test
Unit testUnit test
Unit test
Tran Duc
 
Automation Testing
Automation TestingAutomation Testing
Automation Testing
Sun Technlogies
 
Software Testing Interview Questions & Answers | Edureka
Software Testing Interview Questions & Answers | EdurekaSoftware Testing Interview Questions & Answers | Edureka
Software Testing Interview Questions & Answers | Edureka
Edureka!
 
Python unit testing
Python unit testingPython unit testing
Python unit testing
Darryl Sherman
 
Integration tests: use the containers, Luke!
Integration tests: use the containers, Luke!Integration tests: use the containers, Luke!
Integration tests: use the containers, Luke!
Roberto Franchini
 
Qa in CI/CD
Qa in CI/CDQa in CI/CD
Qa in CI/CD
Adsmurai
 
Unit and integration Testing
Unit and integration TestingUnit and integration Testing
Unit and integration Testing
David Berliner
 
Introduction to selenium
Introduction to seleniumIntroduction to selenium
Introduction to selenium
Khaja Moiz Uddin
 
Monster JavaScript Course - 50+ projects and applications
Monster JavaScript Course - 50+ projects and applicationsMonster JavaScript Course - 50+ projects and applications
Monster JavaScript Course - 50+ projects and applications
Laurence Svekis ✔
 
Regression testing
Regression testingRegression testing
Regression testing
gokilabrindha
 
Test Automation
Test AutomationTest Automation
Test Automation
rockoder
 
Selenium (1)
Selenium (1)Selenium (1)
Selenium (1)
onlinemindq
 

What's hot (20)

End to end testing - strategies
End to end testing - strategiesEnd to end testing - strategies
End to end testing - strategies
 
Automated Testing vs Manual Testing
Automated Testing vs Manual TestingAutomated Testing vs Manual Testing
Automated Testing vs Manual Testing
 
Automation testing
Automation testingAutomation testing
Automation testing
 
Test Automation Frameworks: Assumptions, Concepts & Tools
Test Automation Frameworks: Assumptions, Concepts & ToolsTest Automation Frameworks: Assumptions, Concepts & Tools
Test Automation Frameworks: Assumptions, Concepts & Tools
 
Oracle APEX Social Login
Oracle APEX Social LoginOracle APEX Social Login
Oracle APEX Social Login
 
Data Driven Framework in Selenium
Data Driven Framework in SeleniumData Driven Framework in Selenium
Data Driven Framework in Selenium
 
Integration testing for microservices with Spring Boot
Integration testing for microservices with Spring BootIntegration testing for microservices with Spring Boot
Integration testing for microservices with Spring Boot
 
Automation - web testing with selenium
Automation - web testing with seleniumAutomation - web testing with selenium
Automation - web testing with selenium
 
Unit test
Unit testUnit test
Unit test
 
Automation Testing
Automation TestingAutomation Testing
Automation Testing
 
Software Testing Interview Questions & Answers | Edureka
Software Testing Interview Questions & Answers | EdurekaSoftware Testing Interview Questions & Answers | Edureka
Software Testing Interview Questions & Answers | Edureka
 
Python unit testing
Python unit testingPython unit testing
Python unit testing
 
Integration tests: use the containers, Luke!
Integration tests: use the containers, Luke!Integration tests: use the containers, Luke!
Integration tests: use the containers, Luke!
 
Qa in CI/CD
Qa in CI/CDQa in CI/CD
Qa in CI/CD
 
Unit and integration Testing
Unit and integration TestingUnit and integration Testing
Unit and integration Testing
 
Introduction to selenium
Introduction to seleniumIntroduction to selenium
Introduction to selenium
 
Monster JavaScript Course - 50+ projects and applications
Monster JavaScript Course - 50+ projects and applicationsMonster JavaScript Course - 50+ projects and applications
Monster JavaScript Course - 50+ projects and applications
 
Regression testing
Regression testingRegression testing
Regression testing
 
Test Automation
Test AutomationTest Automation
Test Automation
 
Selenium (1)
Selenium (1)Selenium (1)
Selenium (1)
 

Similar to OCJP Samples Questions: Exceptions and assertions

Java concurrency questions and answers
Java concurrency questions and answers Java concurrency questions and answers
Java concurrency questions and answers
CodeOps Technologies LLP
 
Java programs
Java programsJava programs
Multiple Choice Questions for Java interfaces and exception handling
Multiple Choice Questions for Java interfaces and exception handlingMultiple Choice Questions for Java interfaces and exception handling
Multiple Choice Questions for Java interfaces and exception handling
Abishek Purushothaman
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
AmbigaMurugesan
 
Java Quiz - Meetup
Java Quiz - MeetupJava Quiz - Meetup
Java Quiz - Meetup
CodeOps Technologies LLP
 
Review Questions for Exam 10182016 1. public class .pdf
Review Questions for Exam 10182016 1. public class .pdfReview Questions for Exam 10182016 1. public class .pdf
Review Questions for Exam 10182016 1. public class .pdf
mayorothenguyenhob69
 
java exception.pptx
java exception.pptxjava exception.pptx
java exception.pptx
SukhpreetSingh519414
 
OCP Java SE 8 Exam - Sample Questions - Java Streams API
OCP Java SE 8 Exam - Sample Questions - Java Streams APIOCP Java SE 8 Exam - Sample Questions - Java Streams API
OCP Java SE 8 Exam - Sample Questions - Java Streams API
Ganesh Samarthyam
 
Exception Handling notes in java exception
Exception Handling notes in java exceptionException Handling notes in java exception
Exception Handling notes in java exception
Ratnakar Mikkili
 
MODULE5_EXCEPTION HANDLING.docx
MODULE5_EXCEPTION HANDLING.docxMODULE5_EXCEPTION HANDLING.docx
MODULE5_EXCEPTION HANDLING.docx
VeerannaKotagi1
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
nehakumari0xf
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
kashyapneha2809
 
Exception Handling
Exception HandlingException Handling
Exception Handling
Sunil OS
 
Chap12
Chap12Chap12
Chap12
Terry Yoast
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
BHUVIJAYAVELU
 
Exceptions
ExceptionsExceptions
Exceptions
Soham Sengupta
 
130410107010 exception handling
130410107010 exception handling130410107010 exception handling
130410107010 exception handling
Hemant Chetwani
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
Md. Tanvir Hossain
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
RubaNagarajan
 
9781439035665 ppt ch11
9781439035665 ppt ch119781439035665 ppt ch11
9781439035665 ppt ch11
Terry Yoast
 

Similar to OCJP Samples Questions: Exceptions and assertions (20)

Java concurrency questions and answers
Java concurrency questions and answers Java concurrency questions and answers
Java concurrency questions and answers
 
Java programs
Java programsJava programs
Java programs
 
Multiple Choice Questions for Java interfaces and exception handling
Multiple Choice Questions for Java interfaces and exception handlingMultiple Choice Questions for Java interfaces and exception handling
Multiple Choice Questions for Java interfaces and exception handling
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Java Quiz - Meetup
Java Quiz - MeetupJava Quiz - Meetup
Java Quiz - Meetup
 
Review Questions for Exam 10182016 1. public class .pdf
Review Questions for Exam 10182016 1. public class .pdfReview Questions for Exam 10182016 1. public class .pdf
Review Questions for Exam 10182016 1. public class .pdf
 
java exception.pptx
java exception.pptxjava exception.pptx
java exception.pptx
 
OCP Java SE 8 Exam - Sample Questions - Java Streams API
OCP Java SE 8 Exam - Sample Questions - Java Streams APIOCP Java SE 8 Exam - Sample Questions - Java Streams API
OCP Java SE 8 Exam - Sample Questions - Java Streams API
 
Exception Handling notes in java exception
Exception Handling notes in java exceptionException Handling notes in java exception
Exception Handling notes in java exception
 
MODULE5_EXCEPTION HANDLING.docx
MODULE5_EXCEPTION HANDLING.docxMODULE5_EXCEPTION HANDLING.docx
MODULE5_EXCEPTION HANDLING.docx
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Chap12
Chap12Chap12
Chap12
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Exceptions
ExceptionsExceptions
Exceptions
 
130410107010 exception handling
130410107010 exception handling130410107010 exception handling
130410107010 exception handling
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
 
9781439035665 ppt ch11
9781439035665 ppt ch119781439035665 ppt ch11
9781439035665 ppt ch11
 

Recently uploaded

Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Paul Brebner
 
Secure-by-Design Using Hardware and Software Protection for FDA Compliance
Secure-by-Design Using Hardware and Software Protection for FDA ComplianceSecure-by-Design Using Hardware and Software Protection for FDA Compliance
Secure-by-Design Using Hardware and Software Protection for FDA Compliance
ICS
 
Building API data products on top of your real-time data infrastructure
Building API data products on top of your real-time data infrastructureBuilding API data products on top of your real-time data infrastructure
Building API data products on top of your real-time data infrastructure
confluent
 
TheFutureIsDynamic-BoxLang-CFCamp2024.pdf
TheFutureIsDynamic-BoxLang-CFCamp2024.pdfTheFutureIsDynamic-BoxLang-CFCamp2024.pdf
TheFutureIsDynamic-BoxLang-CFCamp2024.pdf
Ortus Solutions, Corp
 
ppt on the brain chip neuralink.pptx
ppt  on   the brain  chip neuralink.pptxppt  on   the brain  chip neuralink.pptx
ppt on the brain chip neuralink.pptx
Reetu63
 
ACE - Team 24 Wrapup event at ahmedabad.
ACE - Team 24 Wrapup event at ahmedabad.ACE - Team 24 Wrapup event at ahmedabad.
ACE - Team 24 Wrapup event at ahmedabad.
Maitrey Patel
 
The Role of DevOps in Digital Transformation.pdf
The Role of DevOps in Digital Transformation.pdfThe Role of DevOps in Digital Transformation.pdf
The Role of DevOps in Digital Transformation.pdf
mohitd6
 
Best Practices & Tips for a Successful Odoo ERP Implementation
Best Practices & Tips for a Successful Odoo ERP ImplementationBest Practices & Tips for a Successful Odoo ERP Implementation
Best Practices & Tips for a Successful Odoo ERP Implementation
Envertis Software Solutions
 
42 Ways to Generate Real Estate Leads - Sellxpert
42 Ways to Generate Real Estate Leads - Sellxpert42 Ways to Generate Real Estate Leads - Sellxpert
42 Ways to Generate Real Estate Leads - Sellxpert
vaishalijagtap12
 
What’s New in VictoriaLogs - Q2 2024 Update
What’s New in VictoriaLogs - Q2 2024 UpdateWhat’s New in VictoriaLogs - Q2 2024 Update
What’s New in VictoriaLogs - Q2 2024 Update
VictoriaMetrics
 
Refactoring legacy systems using events commands and bubble contexts
Refactoring legacy systems using events commands and bubble contextsRefactoring legacy systems using events commands and bubble contexts
Refactoring legacy systems using events commands and bubble contexts
Michał Kurzeja
 
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
widenerjobeyrl638
 
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptxOperational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
sandeepmenon62
 
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
kalichargn70th171
 
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
campbellclarkson
 
Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)
alowpalsadig
 
Folding Cheat Sheet #6 - sixth in a series
Folding Cheat Sheet #6 - sixth in a seriesFolding Cheat Sheet #6 - sixth in a series
Folding Cheat Sheet #6 - sixth in a series
Philip Schwarz
 
Stork Product Overview: An AI-Powered Autonomous Delivery Fleet
Stork Product Overview: An AI-Powered Autonomous Delivery FleetStork Product Overview: An AI-Powered Autonomous Delivery Fleet
Stork Product Overview: An AI-Powered Autonomous Delivery Fleet
Vince Scalabrino
 
Streamlining End-to-End Testing Automation
Streamlining End-to-End Testing AutomationStreamlining End-to-End Testing Automation
Streamlining End-to-End Testing Automation
Anand Bagmar
 
Beginner's Guide to Observability@Devoxx PL 2024
Beginner's  Guide to Observability@Devoxx PL 2024Beginner's  Guide to Observability@Devoxx PL 2024
Beginner's Guide to Observability@Devoxx PL 2024
michniczscribd
 

Recently uploaded (20)

Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
 
Secure-by-Design Using Hardware and Software Protection for FDA Compliance
Secure-by-Design Using Hardware and Software Protection for FDA ComplianceSecure-by-Design Using Hardware and Software Protection for FDA Compliance
Secure-by-Design Using Hardware and Software Protection for FDA Compliance
 
Building API data products on top of your real-time data infrastructure
Building API data products on top of your real-time data infrastructureBuilding API data products on top of your real-time data infrastructure
Building API data products on top of your real-time data infrastructure
 
TheFutureIsDynamic-BoxLang-CFCamp2024.pdf
TheFutureIsDynamic-BoxLang-CFCamp2024.pdfTheFutureIsDynamic-BoxLang-CFCamp2024.pdf
TheFutureIsDynamic-BoxLang-CFCamp2024.pdf
 
ppt on the brain chip neuralink.pptx
ppt  on   the brain  chip neuralink.pptxppt  on   the brain  chip neuralink.pptx
ppt on the brain chip neuralink.pptx
 
ACE - Team 24 Wrapup event at ahmedabad.
ACE - Team 24 Wrapup event at ahmedabad.ACE - Team 24 Wrapup event at ahmedabad.
ACE - Team 24 Wrapup event at ahmedabad.
 
The Role of DevOps in Digital Transformation.pdf
The Role of DevOps in Digital Transformation.pdfThe Role of DevOps in Digital Transformation.pdf
The Role of DevOps in Digital Transformation.pdf
 
Best Practices & Tips for a Successful Odoo ERP Implementation
Best Practices & Tips for a Successful Odoo ERP ImplementationBest Practices & Tips for a Successful Odoo ERP Implementation
Best Practices & Tips for a Successful Odoo ERP Implementation
 
42 Ways to Generate Real Estate Leads - Sellxpert
42 Ways to Generate Real Estate Leads - Sellxpert42 Ways to Generate Real Estate Leads - Sellxpert
42 Ways to Generate Real Estate Leads - Sellxpert
 
What’s New in VictoriaLogs - Q2 2024 Update
What’s New in VictoriaLogs - Q2 2024 UpdateWhat’s New in VictoriaLogs - Q2 2024 Update
What’s New in VictoriaLogs - Q2 2024 Update
 
Refactoring legacy systems using events commands and bubble contexts
Refactoring legacy systems using events commands and bubble contextsRefactoring legacy systems using events commands and bubble contexts
Refactoring legacy systems using events commands and bubble contexts
 
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
 
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptxOperational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
 
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
 
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
 
Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)
 
Folding Cheat Sheet #6 - sixth in a series
Folding Cheat Sheet #6 - sixth in a seriesFolding Cheat Sheet #6 - sixth in a series
Folding Cheat Sheet #6 - sixth in a series
 
Stork Product Overview: An AI-Powered Autonomous Delivery Fleet
Stork Product Overview: An AI-Powered Autonomous Delivery FleetStork Product Overview: An AI-Powered Autonomous Delivery Fleet
Stork Product Overview: An AI-Powered Autonomous Delivery Fleet
 
Streamlining End-to-End Testing Automation
Streamlining End-to-End Testing AutomationStreamlining End-to-End Testing Automation
Streamlining End-to-End Testing Automation
 
Beginner's Guide to Observability@Devoxx PL 2024
Beginner's  Guide to Observability@Devoxx PL 2024Beginner's  Guide to Observability@Devoxx PL 2024
Beginner's Guide to Observability@Devoxx PL 2024
 

OCJP Samples Questions: Exceptions and assertions

  • 1. OCP Java SE 8 Exam Sample Questions Exceptions and Assertions Hari Kiran & S G Ganesh
  • 2. Question Consider the following program: class ChainedException { public static void foo() { try { throw new ArrayIndexOutOfBoundsException(); } catch(ArrayIndexOutOfBoundsException oob) { RuntimeException re = new RuntimeException(oob); re.initCause(oob); throw re; } } public static void main(String []args) { try { foo(); } catch(Exception re) { System.out.println(re.getClass()); } } } https://ocpjava.wordpress.com When executed this program from main() by calling foo() method, prints which of the following? A. class java.lang.RuntimeException B. class java.lang.IllegalStateException C. class java.lang.Exception D. class java.lang.ArrayIndexOutOfBou ndsException
  • 3. Answer Consider the following program: class ChainedException { public static void foo() { try { throw new ArrayIndexOutOfBoundsException(); } catch(ArrayIndexOutOfBoundsException oob) { RuntimeException re = new RuntimeException(oob); re.initCause(oob); throw re; } } public static void main(String []args) { try { foo(); } catch(Exception re) { System.out.println(re.getClass()); } } } https://ocpjava.wordpress.com When executed this program from main() by calling foo() method, prints which of the following? A. class java.lang.RuntimeException B. class java.lang.IllegalStateException C. class java.lang.Exception D. class java.lang.ArrayIndexOutOfBoun dsException
  • 4. Explanation B. class java.lang.IllegalStateException In the expression new RuntimeException(oob);, the exception object oob is already chained to the RuntimeException object. The method initCause() cannot be called on an exception object that already has an exception object chained during the constructor call. Hence, the call re.initCause(oob); results in initCause() throwing an IllegalStateException . https://ocpjava.wordpress.com
  • 5. Question Consider the following program: class EHBehavior { public static void main(String []args) { try { int i = 10/0; // LINE A System.out.print("after throw -> "); } catch(ArithmeticException ae) { System.out.print("in catch -> "); return; } finally { System.out.print("in finally -> "); } System.out.print("after everything"); } } Which one of the following options best describes the behaviour of this program? A. The program prints the following: in catch -> in finally -> after everything B. The program prints the following: after throw -> in catch -> in finally -> after everything C. The program prints the following: in catch -> after everything D. The program prints the following: in catch -> in finally -> https://ocpjava.wordpress.com
  • 6. Answer Consider the following program: class EHBehavior { public static void main(String []args) { try { int i = 10/0; // LINE A System.out.print("after throw -> "); } catch(ArithmeticException ae) { System.out.print("in catch -> "); return; } finally { System.out.print("in finally -> "); } System.out.print("after everything"); } } Which one of the following options best describes the behaviour of this program? A. The program prints the following: in catch -> in finally -> after everything B. The program prints the following: after throw -> in catch -> in finally -> after everything C. The program prints the following: in catch -> after everything D. The program prints the following: in catch -> in finally -> https://ocpjava.wordpress.com
  • 7. Explanation D . The program prints the following: in catch -> in finally -> The statement println("after throw -> "); will never be executed since the line marked with the comment LINE A throws an exception. The catch handles ArithmeticException , so println("in catch -> "); will be executed. Following that, there is a return statement, so the function returns. But before the function returns, the finally statement should be called, hence the statement println("in finally -> "); will get executed. So, the statement println("after everything"); will never get executed https://ocpjava.wordpress.com
  • 8. Question Consider the following program: import java.util.Scanner; class AutoCloseableTest { public static void main(String []args) { try (Scanner consoleScanner = new Scanner(System.in)) { consoleScanner.close(); // CLOSE consoleScanner.close(); } } } Which one of the following statements is correct? A. This program terminates normally without throwing any exceptions B. This program throws an IllegalStateException C. This program throws an IOException D. This program throws an AlreadyClosedException https://ocpjava.wordpress.com
  • 9. Answer Consider the following program: import java.util.Scanner; class AutoCloseableTest { public static void main(String []args) { try (Scanner consoleScanner = new Scanner(System.in)) { consoleScanner.close(); // CLOSE consoleScanner.close(); } } } Which one of the following statements is correct? A. This program terminates normally without throwing any exceptions B. This program throws an IllegalStateException C. This program throws an IOException D. This program throws an AlreadyClosedException https://ocpjava.wordpress.com
  • 10. Explanation A . This program terminates normally without throwing any exceptions The try-with-resources statement internally expands to call the close() method in the finally block. If the resource is explicitly closed in the try block, then calling close() again does not have any effect. From the description of the close() method in the AutoCloseable interface: “Closes this stream and releases any system resources associated with it. If the stream is already closed, then invoking this method has no effect.” https://ocpjava.wordpress.com
  • 11. Question Consider the following program: class AssertionFailure { public static void main(String []args) { try { assert false; } catch(RuntimeException re) { System.out.println("RuntimeException"); } catch(Exception e) { System.out.println("Exception"); } catch(Error e) { // LINE A System.out.println("Error" + e); } catch(Throwable t) { System.out.println("Throwable"); } } } https://ocpjava.wordpress.com This program is invoked from the command line as follows: java AssertionFailure Choose one of the following options describes the behaviour of this program: A. Prints "RuntimeException" in console B. Prints "Exception" C. Prints "Error" D. Prints "Throwable" E. Does not print any output on console
  • 12. Answer Consider the following program: class AssertionFailure { public static void main(String []args) { try { assert false; } catch(RuntimeException re) { System.out.println("RuntimeException"); } catch(Exception e) { System.out.println("Exception"); } catch(Error e) { // LINE A System.out.println("Error" + e); } catch(Throwable t) { System.out.println("Throwable"); } } } https://ocpjava.wordpress.com This program is invoked from the command line as follows: java AssertionFailure Choose one of the following options describes the behaviour of this program: A. Prints "RuntimeException" in console B. Prints "Exception" C. Prints "Error" D. Prints "Throwable" E. Does not print any output on console
  • 13. Explanation E . Does not print any output on the console By default, assertions are disabled. If -ea (or the - enableassertions option to enable assertions), then the program would have printed "Error" since the exception thrown in the case of assertion failure is java.lang.AssertionError , which is derived from the Error class https://ocpjava.wordpress.com
  • 14. Question Consider the following class hierarchy from the package javax.security.auth.login and answer the questions. Which of the following handlers that makes use of multi-catch exception handler feature will compile without errors? A. catch (AccountException | LoginException exception) B. catch (AccountException | AccountExpiredException exception) C. catch (AccountExpiredException | AccountNotFoundException exception) D. catch (AccountExpiredException exception1 | AccountNotFoundException exception2) https://ocpjava.wordpress.com
  • 15. Answer Consider the following class hierarchy from the package javax.security.auth.login and answer the questions. Which of the following handlers that makes use of multi-catch exception handler feature will compile without errors? A. catch (AccountException | LoginException exception) B. catch (AccountException | AccountExpiredException exception) C. catch (AccountExpiredException | AccountNotFoundException exception) D. catch (AccountExpiredException exception1 | AccountNotFoundException exception2) https://ocpjava.wordpress.com
  • 16. Explanation C . catch (A ccountExpiredException | A ccountNotFoundException exception) For A and B, the base type handler is provided with the derived type handler, hence the multi-catch is incorrect. For D, the exception name exception1 is redundant and will result in a syntax error. C is the correct option and this will compile fine without errors. https://ocpjava.wordpress.com
  • 17. • Check out our latest book for OCPJP 8 exam preparation • http://amzn.to/1NNtho2 • www.apress.com/9781484218358 (download source code here) • https://ocpjava.wordpress.com (more ocpjp 8 resources here) http://facebook.com/ocpjava