0% found this document useful (0 votes)
3 views

Exception Handling

The document explains the behavior of try, catch, and finally blocks in Java, emphasizing that a finally block must always be associated with a try block. It also discusses the differences between final, finally, and finalize, as well as the handling of checked and unchecked exceptions in method overriding. Additionally, it covers the rules for throwing exceptions and the significance of exception handling in robust programming.

Uploaded by

Utkarsh Gupta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Exception Handling

The document explains the behavior of try, catch, and finally blocks in Java, emphasizing that a finally block must always be associated with a try block. It also discusses the differences between final, finally, and finalize, as well as the handling of checked and unchecked exceptions in method overriding. Additionally, it covers the rules for throwing exceptions and the significance of exception handling in robust programming.

Uploaded by

Utkarsh Gupta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

If an exception is thrown prior to the try block, the finally code will not execute.

The finally
block always executes when the try block exits. So you can use finally without catch
but you must use try.

The reason why you cannot have a finally without a try is because you could have
multiple finally statements in the same scope and the try indicates what block of code
the finally pertains to in case an error occurs.
Another interesting feature of the finally is that it must execute no matter what when
the try is entered. For example what if you use a goto to skip over
your finally statement? If the goto is inside of the try it will execute
the finally statement however if the goto is above/outside the try statement then it will
skip the finally code. finally is relevant only to the code that is surrounded in the try. If
you have no try then the finally is not relevant to anything.

The code within the finally block is guaranteed to execute if program control flow enters
the corresponding try block. So it makes no sense to have a finally without a try.
The only exception to this is if the program encounters a System.exit(...) call before
the finally block, as that shuts down the virtual machine.

We can have only one finally block with a try-catch statement.

What statements can exist in between try, catch and finally blocks?

No, try, catch and finally forms a single unit and no other statements should
exist in between try, catch and finally blocks

Are we allowed to use only try block without a catch and finally blocks?

Prior to Java 7:
No, it is not allowed. If used it shows compilation error. The try block must be
followed by a catch block or finally block.

After Java 7 (Correct Answer):


Yes, it is possible to have a try block without a catch and finally blocks. The
introduction of try-with-resources concept makes it possible.
The only constraint is resources which we are passing as a parameter in try
block must implement AutoCloseable interface.
What is the difference between final, finally and finalize in java?

final keyword:
By declaring a variable as final, the value of final variable cannot be changed.
By declaring a method as final, method cannot be overridden.
By declaring a class as final, class cannot be extended.

finally:
Used after try or try-catch block, will get executed after the try and catch
blocks without considering whether an exception is thrown or not.

finalize:
Finalize method is the method that Garbage Collector always calls just before
the deletion/destroying the object which is no longer in use in the code

Why it is always recommended that clean up activities like closing the


DB connections and I/O resources to keep inside a finally block?

finally block will always be executed except one scenario as discussed above
in Q3. By ensuring the cleanup operations in finally block, you will assure that
those operations will be always executed irrespective of whether an exception
has occurred or not.

What will happen if we override a superclass method which is throwing


an unchecked exception with a checked exception in the subclass?

If the overridden method throwing an unchecked exception, then the subclass


overriding method must have the same exception or any other unchecked
exceptions. If you are trying to throw checked exception with subclass
overriding method then it will give a compilation error.

Rule of thumb : An overriding method (subclass method) can not throw a


broader exception than an overridden method (superclass method).
Why do you think Checked Exception exists in Java, since we can
also convey error using RuntimeException ?
This is a controversial question and you need to be careful while answering
this interview question. Though they will definitely like to hear your opinion,
what they are mostly interested in convincing reason. One of the reason I
see is that its a design decision, which is influenced by experience in
programming language prior to Java e.g. C++. Most of checked exceptions
are in java.io package, which make sense because if you request any
system resource and its not available, than a robust program must be able to
handle that situation gracefully. By declaring IOException as checked
Exception, Java ensures that your provide that gracefully exception handling.
Another possible reason could be to ensuring that system resources like file
descriptors, which are limited in numbers, should be released as soon as you
are done with that using catch or finally block.

Checked exceptions are also caught during runtime only. But there are certain
exceptions which the JVM can't decide what action to be taken when they occur. So,
these are categorized into checked exceptions. The user has to mention in prior
what action to be taken if these occur. That's why Checked.

Should we make our custom exceptions checked or unchecked?

If a client can reasonably be expected to recover from an exception, make it a


checked exception. If a client cannot do anything to recover from the exception,
make it an unchecked exception.
Is There Any Way of Throwing a Checked
Exception from a Method That Does Not Have
a Throws Clause?
Yes. We can take advantage of the type erasure performed by the
compiler and make it think we are throwing an unchecked
exception, when, in fact; we're throwing a checked exception:
1 public <T extends Throwable> T sneakyThrow(Throwable ex) throws T {
2 throw (T) ex;
3 }
4
5 public void methodWithoutThrows() {
this.<RuntimeException>sneakyThrow(new Exception("Checked Exception"));
6
}
7

What Are the Rules We Need to Follow When


Overriding a Method That Throws an
Exception?
When the parent class method doesn't throw any exceptions, the
child class method can't throw any checked exception, but it may
throw any unchecked.
When the parent class method throws one or more checked
exceptions, the child class method can throw any unchecked
exception; all, none or a subset of the declared checked exceptions,
and even a greater number of these as long as they have the same
scope or narrower.
Here's an example code that successfully follows the previous rule:
1 class Parent {
void doSomething() throws IOException, ParseException {
2
// ...
3 }
4
5 void doSomethingElse() throws IOException {
6 // ...
7 }
}
8
9
10
11 class Child extends Parent {
12 void doSomething() throws IOException {
13 // ...
}
14
15 void doSomethingElse() throws FileNotFoundException, EOFException {
16 // ...
17 }
18 }
19
Note that both methods respect the rule. The first throws fewer
exceptions than the overridden method, and the second, even
though it throws more; they're narrower in scope.
However, if we try to throw a checked exception that the parent
class method doesn't declare or we throw one with a broader scope;
we'll get a compilation error:
class Parent {
void doSomething() throws FileNotFoundException {
// ...
}
}

class Child extends Parent {


void doSomething() throws IOException {
// Compilation error
}
}

When the parent class method has a throws clause with an


unchecked exception, the child class method can throw none or any
number of unchecked exceptions, even though they are not related.

Checked and unchecked

BASIS FOR
CHECKED EXCEPTION UNCHECKED EXCEPTION
COMPARISON

Basic The compiler checks the checked exception. The compiler does not check the
BASIS FOR
CHECKED EXCEPTION UNCHECKED EXCEPTION
COMPARISON

Unchecked exception.

Class of Except "RuntimeException" class all the child "RuntimeException" class and its

Exception classes of the class "Exception", and the child classes, are"Unchecked

"Error" class and its child classes are Exceptions".

Checked Exception.

Handling If we do not handle the checked exception, Even if we do not handle the

then the compiler objects. unchecked exception, the compiler

doesn't object.

Compilation The program doesn't compile if there is an The program compiles successfully

unhandled checked exception in the even if there is an unhandled

program code. unchecked exception in the program

code.

How JVM Handle exception

Default Exception Handling : Whenever inside a method, if an exception has


occurred, the method creates an Object known as Exception Object and hands it off to
the run-time system(JVM). The exception object contains name and description of the
exception, and current state of the program where exception has occurred. Creating the
Exception Object and handling it to the run-time system is called throwing an
Exception.There might be the list of the methods that had been called to get to the
method where exception was occurred. This ordered list of the methods is called Call
Stack.Now the following procedure will happen.
 The run-time system searches the call stack to find the method that contains block
of code that can handle the occurred exception. The block of the code is
called Exception handler.
 The run-time system starts searching from the method in which exception
occurred, proceeds through call stack in the reverse order in which methods were
called.
 If it finds appropriate handler then it passes the occurred exception to it.
Appropriate handler means the type of the exception object thrown matches the
type of the exception object it can handle.
 If run-time system searches all the methods on call stack and couldn’t have found
the appropriate handler then run-time system handover the Exception Object
to default exception handler , which is part of run-time system. This handler
prints the exception information in the following format and terminates
program abnormally.

THROWS AND THROW

THROW THROWS

throws keyword is used to declare

throw keyword is used to throw an one or more exceptions, separated

exception explicitly. by commas.

Only single exception is thrown by using Multiple exceptions can be thrown by

throw. using throws.

throws keyword is used with the

throw keyword is used within the method. method signature.


Syntax wise throw keyword is followed by Syntax wise throws keyword is

the instance variable. followed by exception class names.

Checked exception cannot be For the propagation checked

propagated using throw only.Unchecked exception must use throws keyword

exception can be propagated using followed by specific exception class

throw. name.

Exception Handling with Method Overriding


in Java

1. If SuperClass does not declare an exception, then the SubClass can only
declare unchecked exceptions, but not the checked exceptions.
2. If SuperClass declares an exception, then the SubClass can only declare the
child exceptions of the exception declared by the SuperClass, but not any
other exception.
3. If SuperClass declares an exception, then the SubClass can declare without
exception.

When the parent class method doesn't throw any


exceptions, the child class method can't throw any checked
exception, but it may throw any unchecked.

When the parent class method throws one or more checked


exceptions, the child class method can throw any unchecked
exception; all, none or a subset of the declared checked
exceptions, and even a greater number of these as long as
they have the same scope or narrower.

When the parent class method has a throws clause with an


unchecked exception, the child class method can throw none
or any number of unchecked exceptions, even though they
are not related.

You might also like