|
JAVA Interview Questions 34 - 35
|
Back to the list of all Java Interview Questions
|
|
Question 34: If you have a circular reference of objects, but you no longer reference it from an execution thread, will this object
be a potential candidate for garbage collection?
|
Yes. Refer diagram below.
|
|
|
Question 35: Discuss the Java error handling mechanism? What is the difference between Runtime (unchecked) exceptions
and checked exceptions? What is the implication of catching all the exceptions with the type “Exception”?
|
Errors: When a dynamic linking failure or some other “hard” failure in the virtual machine occurs, the virtual
machine throws an Error. Typical Java programs should not catch Errors. In addition, it’s unlikely that typical Java
programs will ever throw Errors either.
Exceptions: Most programs throw and catch objects that derive from the Exception class. Exceptions indicate
that a problem occurred but that the problem is not a serious JVM problem. An Exception class has many
subclasses. These descendants indicate various types of exceptions that can occur. For example,
NegativeArraySizeException indicates that a program attempted to create an array with a negative size. One
exception subclass has special meaning in the Java language: RuntimeException. All the exceptions except
RuntimeException are compiler checked exceptions. If a method is capable of throwing a checked exception it
must declare it in its method header or handle it in a try/catch block. Failure to do so raises a compiler error. So
checked exceptions can, at compile time, greatly reduce the occurrence of unhandled exceptions surfacing at
runtime in a given application at the expense of requiring large throws declarations and encouraging use of poorlyconstructed
try/catch blocks. Checked exceptions are present in other languages like C++, C#, and Python.
|
|
Runtime Exceptions (unchecked exception)
A RuntimeException class represents exceptions that occur within the Java virtual machine (during runtime). An
example of a runtime exception is NullPointerException. The cost of checking for the runtime exception often
outweighs the benefit of catching it. Attempting to catch or specify all of them all the time would make your code
unreadable and unmaintainable. The compiler allows runtime exceptions to go uncaught and unspecified. If you
like, you can catch these exceptions just like other exceptions. However, you do not have to declare it in your
“throws" clause or catch it in your catch clause. In addition, you can create your own RuntimeException
subclasses and this approach is probably preferred at times because checked exceptions can complicate method
signatures and can be difficult to follow.
|
Back to the list of all Java Interview Questions
|