Exception Handling Questions Flashcards
What is an exception?
Exceptions are abnormal conditions that arise during execution of the program. It may occur due to wrong user input or wrong logic written by programmer.
Which package has definitions for all the exception classes?
Java.lang.Exception
What are the types of exceptions?
Checked exceptions
Unchecked exceptions
What are checked exceptions?
These exceptions must be handled by programmer otherwise the program would throw a compilation error.
What are unchecked exceptions?
It is up to the programmer to write the code in such a way to avoid unchecked exceptions. You would not get a compilation error if you do not handle these exceptions. These exceptions occur at runtime.
What is the difference between Error and Exception?
Error: Mostly a system issue. It always occur at run time and must be resolved in order to proceed further.
Exception: Mostly an input data issue or wrong logic in code. Can occur at compile time or run time.
What is throw keyword in exception handling?
The throw keyword is used for throwing user defined or pre-defined exception.
What is throws keyword?
If a method does not handle a checked exception, the method must declare it using the throwskeyword. The throws keyword appears at the end of a method’s signature.
Can static block throw exception?
Yes, A static block can throw exceptions. It has its own limitations: It can throw only Runtime exception (Unchecked exceptions), In order to throw checked exceptions you can use a try-catch block inside it.
What is finally block?
Finally block is a block of code that always executes, whether an exception occurs or not. Finally block follows try block or try-catch block.
Q) ClassNotFoundException vs NoClassDefFoundError?
1) ClassNotFoundException occurs when loader could not find the required class in class path.
2) NoClassDefFoundError occurs when class is loaded in classpath, but one or more of the class which are required by other class, are removed or failed to load by compiler.
Can we have a try block without catch or finally block?
No, we cannot have a try block without catch or finally block. We must have either one of them or both.
Can we have multiple catch blocks following a single try block?
Yes we can have multiple catch blocks in order to handle more than one exception.
Is it possible to have finally block without catch block?
Yes, we can have try block followed by finally block without even using catch blocks in between.
When does a finally block does not get executed?
The only time finally won’t be called is if you call System.exit() or if the JVM crashes first.
Can we handle more than one exception in a single catch block?
Yes we can do that using if-else statement but it is not considered as a good practice. We should have one catch block for one exception.