0% found this document useful (0 votes)
6 views9 pages

Java Exception Handling Explained

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)
6 views9 pages

Java Exception Handling Explained

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

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 [Link](...) 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 [Link] 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
[Link] 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
[Link] 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 [Link] 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.

Common questions

Powered by AI

When an exception occurs in a method, the Java Virtual Machine (JVM) creates an Exception Object that contains the name, description, and the program state when the exception occurred. It then searches the call stack for an appropriate exception handler. If none is found, the exception is handed over to the default exception handler, which prints error information and terminates the program abnormally. This process ensures that unhandled exceptions do not silently fail and inadvertently cause more significant issues .

The concept of sneaky throws in Java exploits the type erasure system, allowing a programmer to throw a checked exception from a method that doesn't declare a throws clause. It uses type casting to cast a checked exception to an unchecked one, often used when the programmer wants to avoid explicitly declaring every possible checked exception in a method signature. This technique involves generic types and undermines Java's checked exception mechanism, and should be used with caution as it can impact code readability and intent .

When a superclass method declares an exception, the subclass method can only declare the same or narrower exceptions (i.e., child exceptions of the declared exception by the superclass). It cannot introduce new checked exceptions that are broader than the ones declared in the superclass. If the superclass method doesn't declare any exceptions, the subclass can only declare unchecked exceptions in its overriding method .

Finally blocks are designed to execute clean-up operations that must run when the try block exits, regardless of whether an exception was thrown. Without an associated try block, the finally block would have no context for when to execute its code. The try block signifies the scope in which the finally block is relevant. If there is no try block, there is potentially nothing for the finally code to execute after, making it redundant .

The try-with-resources statement, introduced in Java 7, simplifies resource management by automatically closing resources once the try block finishes execution. This feature ensures that resources like files and database connections are closed reliably and promptly, greatly reducing boilerplate code and potential resource leaks. Unlike the traditional try-catch-finally block which requires explicit resource handling, try-with-resources automatically handles closing resources by requiring resources to implement the AutoCloseable interface .

Declaring too many exceptions in a method signature can lead to cluttered and complex code that is hard to read and maintain. It may also obscure which exceptions are meaningful for the calling code to handle. Moreover, it can lead to poor encapsulation as the callers need to be aware of all the potential exceptions, coupling the exception handling logic tightly with the implementation details of the method. This reduces flexibility and the ability to change the implementation without affecting all calling code .

Java uses checked exceptions, particularly within the java.io package, to ensure that programs handle situations like unavailable system resources gracefully. By making exceptions like IOException checked, Java requires programs to either catch these exceptions or declare them, encouraging programmers to implement error handling and thus prevent resource leaks. This is integral in managing limited resources like file descriptors, ensuring they are released as soon as they are not needed .

The throw keyword is used within a method to explicitly throw an exception, whereas the throws keyword is used in the method signature to declare that a method might throw one or more exceptions. The throw keyword follows the syntax of object instantiation, indicating which specific exception instance is being thrown. In contrast, throws is followed by exception class names and is used to inform method callers of the potential exceptions that need to be handled. Throw is used within the method body, while throws is used in declaration to signal exceptions that could be passed upwards in the call stack .

Checked exceptions are recommended when the client code is expected to recover from the exception. This makes sure developers handle such conditions explicitly at compile time. Conversely, unchecked exceptions should be used when recovery from exceptions is not feasible or the error is due to a programming error (e.g., null pointer, out of bounds), and thus shouldn't be forced in the exception handling during compile time .

The final keyword in Java can be applied to variables, methods, and classes to indicate that a value cannot be modified, a method cannot be overridden, or a class cannot be subclassed, respectively. The finally block is part of exception handling used to execute important code such as clean-up operations and is always executed after the try-catch block regardless of whether an exception occurred. The finalize method, now deprecated, was used by the garbage collector to perform cleanup operations before collecting an object, though it was unreliable and provided no guarantees on when it would be called .

You might also like