Core java interview Questions You'll Most Likely Be Asked (Second Edition)


Download 1.52 Mb.
Pdf ko'rish
bet50/171
Sana07.01.2023
Hajmi1.52 Mb.
#1081886
1   ...   46   47   48   49   50   51   52   53   ...   171
Bog'liq
Core JAVA Interview Questions Youll M...

127.
a.
b.
128.
done. Next, control transfers outside the finally block to Line 6
and the code prints Thank You!!
Suppose you have a method called myMethod with some
code that can throw a checked Exception. How will you
handle this in the code?
Answer:
If a method throws a checked exception, there are two ways that
it can be handled?
Use try/catch within the method body as follows:
public void myMethod(){
try {
//code here
}
catch (CheckedException e) {
}
}
Here, when the code throws a CheckedException, it is caught
by the catch block within the method
Use throws clause with the method declaration
public void myMethod () throws CheckedException{
//code here
}
Here, when the code throws a CheckedException, it is thrown
outside the method by the throws clause. So, the code that
invokes this method needs to handle the exception.
What is the use of “finally” clause? Give an example.


129.



130.
Answer:
Any code that needs to be always executed irrespective of
whether an exception occurs or not, should be placed within the
finally clause. So, for example clean–up code like closing
database connections or files on the file system or other
resources can be placed in the finally clause. If such code is
placed in the try block, there is a possibility that it may not
execute if an exception occurs. So, to ensure that such code is
always executed, it needs to be placed in the finally block.
Explain the differences between Error and Exception.
Answer:
The java.lang.Throwable is the superclass of all the
exception classes. It has two sub–classes, Exception and Error.
There are several differences between the two:
An Exception represents programmatic errors that are caused
by the application itself like accessing a null value, dividing by
0, error while writing to a file, etc. An Error represents errors
that occur outside your code within the runtime environment
like running out of memory, etc.
Exceptions are conditions that an application can handle and
recover from. Errors on the other hand are abnormal
conditions that indicate serious problems that an application
cannot recover from.
Exceptions are both checked as well as unchecked. Checked
exceptions need to be handled or specified within the throws
clause in the method declaration. Errors on the other hand are
always unchecked and need not be declared in the throws
clause.

Download 1.52 Mb.

Do'stlaringiz bilan baham:
1   ...   46   47   48   49   50   51   52   53   ...   171




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling