Professional Documents
Culture Documents
Day 4 Viva
Day 4 Viva
Advantages of Exceptions
readFile {
open the file;
allocate that much memory;
read the file into memory;
close the file;
}
At first glance, this function seems simple
enough, but it ignores all the following potential
errors.
errorCodeType readFile {
initialize errorCode = 0;
readFile {
try {
open the file;
determine its size;
allocate that much memory;
read the file into memory;
close the file;
} catch (fileOpenFailed) {
doSomething;
} catch (memoryAllocationFailed) {
doSomething;
} catch (readFailed) {
doSomething;
} catch (fileCloseFailed) {
doSomething;
}
}
Note that exceptions don't spare you the effort of
doing the work of detecting, reporting, and
handling errors, but they do help you organize
the work more effectively.
method1 {
call method2;
}
method2 {
call method3;
}
method3 {
call readFile;
}
Suppose also that method1 is the only method
interested in the errors that might occur within
readFile. Traditional error-notification techniques
force method2 and method3 to propagate the
error codes returned by readFile up the call
stack until the error codes finally reach method1
—the only method that is interested in them.
method1 {
errorCodeType error;
error = call method2;
if (error)
doErrorProcessing;
else
proceed;
}
errorCodeType method2 {
errorCodeType error;
error = call method3;
if (error)
return error;
else
proceed;
}
errorCodeType method3 {
errorCodeType error;
error = call readFile;
if (error)
return error;
else
proceed;
}
method1 {
try {
call method2;
} catch (exception e) {
doErrorProcessing;
}
}
catch (IOException e) {
...
}
catch (IOException e) {
// Output goes to System.err.
e.printStackTrace();
// Send trace to stdout.
e.printStackTrace(System.out);
}
try
{
String s = null;
System.out.println(s.length()); //This
statement throws NullPointerException
}
catch(NullPointerException ex)
{
System.out.println("NullPointerException is
caught here");
B)
try
{
//try block
}
finally
{
//finally block
}
C)
try
{
//try block
}
catch(Exception ex)
{
//catch block
}
finally
{
//finally block
}
If the client can take some alternate action to recover from the
exception, make it a checked exception. If the client cannot do
anything useful, then make the exception unchecked. By useful, it
means, taking steps to recover from the exception and not just logging the exception. To
summarize:
b. Preserve encapsulation.
This converts SQLException to RuntimeException.
If SQLException occurs, the catch clause throws a new
RuntimeException. The execution thread is suspended and the
exception gets reported. Here we are not corrupting our business
object layer with unnecessary exception handling, especially since
it cannot do anything about an SQLException. If
our catch needs the root exception cause, we can make use of
the getCause() method available in all exception classes as of
JDK1.4.
Ans:-