SlideShare a Scribd company logo
1 of 17
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

What's hot (20)

Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
 
Packages,static,this keyword in java
Packages,static,this keyword in javaPackages,static,this keyword in java
Packages,static,this keyword in java
 
Support POO Java première partie
Support POO Java première partieSupport POO Java première partie
Support POO Java première partie
 
Multi Threading
Multi ThreadingMulti Threading
Multi Threading
 
POO Java Chapitre 6 Exceptions
POO Java  Chapitre 6 ExceptionsPOO Java  Chapitre 6 Exceptions
POO Java Chapitre 6 Exceptions
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Polymorphism in Java
Polymorphism in JavaPolymorphism in Java
Polymorphism in Java
 
Exception handling in java
Exception handling  in javaException handling  in java
Exception handling in java
 
Abstraction in java
Abstraction in javaAbstraction in java
Abstraction in java
 
Exception handling
Exception handling Exception handling
Exception handling
 
Functional programming
Functional programmingFunctional programming
Functional programming
 
[OOP - Lec 18] Static Data Member
[OOP - Lec 18] Static Data Member[OOP - Lec 18] Static Data Member
[OOP - Lec 18] Static Data Member
 
Input and Output In C Language
Input and Output In C LanguageInput and Output In C Language
Input and Output In C Language
 
Solve cross cutting concerns with aspect oriented programming (aop)
Solve cross cutting concerns with aspect oriented programming (aop)Solve cross cutting concerns with aspect oriented programming (aop)
Solve cross cutting concerns with aspect oriented programming (aop)
 
Chapitre6: Surcharge des opérateurs
Chapitre6:  Surcharge des opérateursChapitre6:  Surcharge des opérateurs
Chapitre6: Surcharge des opérateurs
 
Deep C
Deep CDeep C
Deep C
 
Java Quiz Questions
Java Quiz QuestionsJava Quiz Questions
Java Quiz Questions
 
Chapitre8: Collections et Enumerations En Java
Chapitre8: Collections et Enumerations En JavaChapitre8: Collections et Enumerations En Java
Chapitre8: Collections et Enumerations En Java
 
Java PRACTICAL file
Java PRACTICAL fileJava PRACTICAL file
Java PRACTICAL file
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
 

Similar to OCP Java SE 8 Exam Sample Questions on Exceptions and Assertions (40

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 handlingAbishek Purushothaman
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaAmbigaMurugesan
 
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 .pdfmayorothenguyenhob69
 
MODULE5_EXCEPTION HANDLING.docx
MODULE5_EXCEPTION HANDLING.docxMODULE5_EXCEPTION HANDLING.docx
MODULE5_EXCEPTION HANDLING.docxVeerannaKotagi1
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024nehakumari0xf
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024kashyapneha2809
 
Exception Handling
Exception HandlingException Handling
Exception HandlingSunil OS
 
Java exception handling
Java exception handlingJava exception handling
Java exception handlingBHUVIJAYAVELU
 
130410107010 exception handling
130410107010 exception handling130410107010 exception handling
130410107010 exception handlingHemant Chetwani
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-ivRubaNagarajan
 
9781439035665 ppt ch11
9781439035665 ppt ch119781439035665 ppt ch11
9781439035665 ppt ch11Terry Yoast
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptionssaman Iftikhar
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertionRakesh Madugula
 

Similar to OCP Java SE 8 Exam Sample Questions on Exceptions and Assertions (40 (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
 
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
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertion
 

Recently uploaded

Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfLivetecs LLC
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noidabntitsolutionsrishis
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....kzayra69
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 

Recently uploaded (20)

Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdf
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 

OCP Java SE 8 Exam Sample Questions on Exceptions and Assertions (40

  • 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