Sei sulla pagina 1di 155

Differences between Checked (compile time exceptions)

and UnChecked (RuntimeExceptions) in java - Definition


www.javamadesoeasy.com /2015/05/checked-compile-time-exceptions-and.html

You are here : Home / Core Java Tutorials / Exceptions Tutorial in java

Contents of page :

checked exceptions
unchecked exceptions
Differences between checked and unchecked exceptions >

checked exceptions
checked exceptions are also known as compileTime exceptions.
Checked exceptions are those which need to be taken care at compile time.

Benefit of using compiletime Exception >


We cannot proceed until we fix compilation issues which are most likely to happen in program, this helps us in
avoiding runtime problems upto lot of extent.
Example- FileNotFoundException - Until we handle this exception, user will face compilation error, because at
runtime there is huge probability of file missing in the directory.

Which classes are which exception?


The class Exception and all its subclasses that are not also subclasses of RuntimeException are checked
exceptions.

Exception propagation >


For propagating checked exceptions method must throw exception by using throws keyword.

unchecked exceptions

unchecked exceptions are also known as runtime exceptions.


Unchecked exceptions are those which need to be taken care at runtime.

Benefit of using RunTime Exception >


Whenever runtime exception occurs execution of program is interrupted, but by handling these kind of exception we
avoid such interruptions and end up giving some meaningful message to user.

Which classes are which exception?


The class RuntimeException and all its subclasses are unchecked exceptions.
Likewise,
The class Error and all its subclasses are unchecked exceptions.

1/3
Exception propagation >
unchecked exceptions are automatically propagated in java.

Differences between checked and unchecked exceptions >

Property checked exception unchecked exception

1 Also known checked exceptions are also known unchecked exceptions are also known as
as as compileTime exceptions. runtime exceptions.

2 Should be Checked exceptions are those which Unchecked exceptions are those which
solved at need to be taken care at compile need to be taken care at runtime.
compile or time.
runtime?

3 Benefit/ We cannot proceed until we fix Whenever runtime exception occurs


Advantage compilation issues which are most execution of program is interrupted, but
likely to happen in program, this helps by handling these kind of exception we
us in avoiding runtime problems upto avoid such interruptions and end up
lot of extent. giving some meaningful message to user.

4 Creating
custom/own
exception class UserException extends class UserException extends
Exception { RuntimeException {
UserException(String s) { UserException(String s) {
super(s); super(s);
} }
} }

By extending java.lang.Exception, we By extending


can create checked exception. java.lang.RuntimeException, we can
create unchecked exception.

5 Exception For propagating checked exceptions unchecked exceptions are automatically


propagation method must throw exception by propagated in java.
using throws keyword.

2/3
6 handling If superclass method throws/declare If superclass method throws/declare
checked checked exception > unchecked >
and
unchecked overridden method of subclass overridden method of subclass
exception can declare/throw narrower can declare/throw any unchecked
while (subclass of) checked /RuntimeException (superclass or
overriding exception (As shown in subclass) (As shown in Program),
superclass Program), or or
method overridden method of subclass overridden method of subclass
cannot declare/throw broader cannot declare/throw any checked
(superclass of) checked exception (As shown in Program),
exception (As shown in
Program), or
overridden method of subclass
can declare/throw any
unchecked /RuntimeException
(As shown in Program)

Which The class Exception and all its The class RuntimeException and all its
classes are subclasses that are not also subclasses are unchecked exceptions.
which type subclasses of RuntimeException are Likewise,
of checked exceptions. The class Error and all its subclasses are
exception? unchecked exceptions.
either
checked or
unchecked
exception?

7 Most SQLException, NullPointerException,


frequently IOException, ArithmeticException
faced ClassNotFoundException ArrayIndexOutOfBoundsException.
exceptions

/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */

Labels: Exception Differences and Similarities Exceptions

3/3
What are checked (compile time exceptions) in java
www.javamadesoeasy.com /2015/11/what-are-checked-compile-time.html

You are here : Home / Core Java Tutorials / Exceptions Tutorial in java

Contents of page >

1) What are checked exceptions in java


2) Advantage/Benefit of using checked/compiletime Exception in java >
3) Example of checked exceptions in java
4) Which classes are which checked exceptions in java?
5) Propagating checked exception (FileNotFoundException) using throws keyword in java >

1) What are checked exceptions in java


checked exceptions are also known as compileTime exceptions.
Checked exceptions are those which need to be taken care at compile time.

2) Advantage/Benefit of using checked/compiletime Exception in java >


We cannot proceed until we f ix compilation issues which are most likely to happen in program , this helps us in
avoiding runtime problems upto lot of extent in java.

3) Example of checked exceptions in java


Example - FileNotFoundException - Until we handle this exception, user will face compilation error, because at
runtime there is huge probability of file missing in the directory.

Most common and frequently occurring checked (compile time) in java >

IOException in java

FileNotFoundException in java

EOFException occurs and how to avoid it in java

SQLException in java

What is java.lang.InterruptedException in java

when java.lang.ClassNotFoundException occurs in java

Solve InvalidClassException in java

4) Which classes are which checked exceptions in java?


1/3
The class Exception and all its subclasses that are not also subclasses of RuntimeException are checked
exceptions.

5) Propagating checked exception (FileNotFoundException) using throws keyword in java >


For propagating checked exceptions method must throw exception by using throws keyword.

Now, ill be explaining you how checked exception was propagated.


Lets see step by step what happened in above program >

JVM called main method


step 1 - main called method1()
step 2 - method1 called method2()
step 3 - method2 called method3()
step 4 - method3 propagated exception to method2() using throws keyword.[because, checked exceptions
are not propagated automatically]
step 5 - method2 propagated exception to method1() using throws keyword.[because, checked exceptions
are not propagated automatically]
step 6 - method2 propagated exception to main() using throws keyword.[because, checked exceptions are
not propagated automatically]
main() propagated exception to JVM using throws keyword.[because, checked exceptions are not
propagated automatically]

2/3
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */

Labels: Core Java

3/3
What are unchecked (RuntimeExceptions) in java
www.javamadesoeasy.com /2015/11/what-are-unchecked-runtimeexceptions-in.html

You are here : Home / Core Java Tutorials / Exceptions Tutorial in java

Contents of page >

1) What are unchecked exceptions in java


2) Advantage/Benefit of using unchecked/RunTime Exception in java >
3) Example of unchecked exceptions in java
4) Which classes are which unchecked exception in java?
5) Propagating unchecked exception (NullPointerException) in java >
6) Let's see how stack of methods is formed >

1) What are unchecked exceptions in java

unchecked exceptions are also known as runtime exceptions.


Unchecked exceptions are those which need to be taken care at runtime.

2) Advantage/Benefit of using unchecked/RunTime Exception in java >


Whenever runtime exception occurs execution of program is interrupted, but by handling these kind of exception we
avoid such interruptions and end up giving some meaningful message to user in java.

3) Example of unchecked exceptions in java

Most common and frequently occurring unchecked (runtime) in java.

What is java.lang.NullPointerException in java, when it occurs,how to handle, avoid and


fix it

NumberFormatException in java

IndexOutOfBoundsException in java

When java.lang.ArrayIndexOutOfBoundsException occurs in java

When java.lang.StringIndexOutOfBoundsException occurs in java

java.lang.ArithmeticException in java - Divide number by zero

When dividing by zero does not throw ArithmeticException in java

When java.lang.IllegalStateException occurs in java


1/3
when java.lang.IllegalMonitorStateException is thrown in java

Solve java.lang.UnsupportedOperationException in java

4) Which classes are which unchecked exception in java?


The class RuntimeException and all its subclasses are unchecked exceptions.
Likewise,
The class Error and all its subclasses are unchecked exceptions.

5) Propagating unchecked exception (NullPointerException) in java >


unchecked exceptions are automatically propagated in java.

Now, ill be explaining you how unchecked exception was propagated.


Lets see step by step what happened in above program >

JVM called main method


step 1 - main called method1()
step 2 - method1 called method2()
step 3 - method2 called method3()
step 4 - method3 automatically propagated exception to method2() [because, unchecked exceptions are
propagated automatically]

2/3
step 5 - method2 automatically propagated exception to method1() [because, unchecked exceptions are
propagated automatically]
step 6 - method2 automatically propagated exception to main() [because, unchecked exceptions are
propagated automatically]
main() automatically propagated exception to JVM [because, unchecked exceptions are propagated
automatically]

6) Let's see how stack of methods is formed >


In the above program, stack is formed and an exception is first thrown
from the top of the stack [ method3() ] and it remains uncaught there,
and starts coming down the stack to previous methods to method2(),
then to method1(), than to main() and it remains uncaught throughout.
exception remains uncaught even after reaching bottom of the stack [
main() ] so it is propagated to JVM and ultimately program is terminated
by throwing exception [ as shown in output ].

Labels: Core Java

3/3
java.lang.Error in exception handling in java - Program to
show StackOverflowError
www.javamadesoeasy.com /2015/05/javalangerror-in-exception-handling-in.html

You are here : Home / Core Java Tutorials / Exceptions Tutorial in java

java.lang.Error

Error is a subclass of Throwable


Error indicates some serious problems that our application should not try to catch.
Errors are abnormal conditions in application.
Error and its subclasses are regarded as unchecked exceptions

Must know :
ThreadDeath is an error which application must not try to catch but it is normal condition.

Why application should not try to catch Error?


Because, in most of cases recovery from an Error is almost impossible. So, application must be allowed to
terminate.
Example>
Lets say errors like OutOfMemoryError and StackOverflowError occur and are caught then JVM might not be able
to free up memory for rest of application to execute, so it will be better if application dont catch these errors and is
allowed to terminate.

Program to show StackOverflowError >


StackOverflowError is thrown when a stack overflow occurs because an application recurses too deeply.

1/2
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class ExceptionTest {
public static void main(String[] args) {
m(); //call recursive method m()
System.out.println("Code after exception handling");
}

static void m() {


try {
//method m() calls itself recursively
m();
} catch (StackOverflowError e) {
e.printStackTrace();
}
}
}
/*OUTPUT
java.lang.StackOverflowError
at ExceptionTest.m(ExceptionTest.java:18)
.
.
.
.
.
.
.
.
Code after exception handling
*/

RELATED LINKS>

5 keyword in java exception handling

try catch finally block in java


throw exception in java

throws exception in java

EXCEPTIONS - Top 60 interview questions and answers in java for fresher and experienced -
detailed explanation with diagrams Set-1 > Q1- Q25

EXCEPTIONS - Top 60 interview questions and answers in java for fresher and experienced -
30 important OUTPUT questions Set-2 > Q26- Q60

Labels: Core Java Exceptions

2/2
try catch finally block in java
www.javamadesoeasy.com /2015/05/try-catch-finally-block-in-java.html

You are here : Home / Core Java Tutorials / Exceptions Tutorial in java

We can enclose exception prone code in >

try-catch block, or
try-finally block, or
try-catch-finally block.

Using try-catch block

try{
//Code to be enclosed in try-catch block
}catch(Exception e){
}

Using try-finally block

try{
//Code to be enclosed in try-finally block
}finally{
}

Using try-catch-finally block

try{
//Code to be enclosed in try-catch-finally block
}catch(Exception e){
}finally{
}

We cannot use try block alone, it must be followed by either catch or finally.
Using only try block will cause compilation error

try{
//only try block will cause compilation error
}

1/3
Likewise, we cannot use catch block alone, it always follows try block.
Using only catch block will cause compilation error

catch{
//only catch block will cause compilation error
}

Likewise, we cannot use finally block alone, it always follows try or try-catch block.
Using only finally block will cause compilation error

finally{
//only finally block will cause compilation error
}

How try-catch block helps us >


With try-catch block we can avoid awkward termination of program.

If any exception occurs and it is not handled properly, rest of the code is not executed >

/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */


public class ExceptionTest {
public static void main(String[] args) {
int i=10/0; //will throw ArithmeticException
System.out.println("Did this line execute?");
}
}
/*OUTPUT
Exception in thread "main" java.lang.ArithmeticException: / by zero
at javaMadeSoEasy.ExceptionTest.main(ExceptionTest.java:4)
*/

In the above program ArithmeticException was thrown at line 4, it wasnt handled properly, so rest of the code didnt
executed.

If any exception occurs and it is handled properly, rest of the code gets executed >

2/3
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class ExceptionTest {
public static void main(String[] args) {
try{
int i=10/0; //will throw ArithmeticException
}catch(Exception e){
System.out.println("Exception handled properly in catch block");
}
System.out.println("Code after exception handling");
}
}
/*OUTPUT
Exception handled properly
Code after exception handling
*/

In the above program ArithmeticException was thrown at line 5, it was handled properly, so rest of the code did
executed.

but by handling these kind of exception we avoid such interruptions and end up giving some meaningful message to
user.

Labels: Core Java Exceptions

3/3
JavaMadeSoEasy.com (JMSE)
www.javamadesoeasy.com /2015/05/finally-block-in-java.html

You are here : Home / Core Java Tutorials / Exceptions Tutorial in java

Contents of page :

try or try-catch block can be followed by finally block >


Features of finally >
finally block is not executed in following scenarios >
Programming time - we will create following programs to demonstrate finally block in java >
Program 1 to show finally block is executed when exception is not thrown.
Program 2 to show finally block is executed when exception is thrown, in this case catch and finally both
blocks are executed.
Program 3 to show finally block is executed when exception is thrown and not handled properly, in this case
catch blocks does not executes, finally block executes alone.
Program 4 to show finally is not executed when System.exit is called.

Bit more about System.exit(n) method >

Program 5 to show what will happen when catch and finally both return some value.
Application of finally block in java programs >

try or try-catch block can be followed by finally block >

try-finally block, or

try{
//Code to be enclosed in try-finally block
}finally{
}

try-catch-finally block.

try{
//Code to be enclosed in try-catch-finally block
}catch(Exception e){
}finally{
}

finally block can can only exist if try or try-catch block is there, finally block cant be used alone in java.
Using only finally block will cause compilation error

1/5
finally{
//only finally block will cause compilation error
}

Features of finally >

finally block is always executed irrespective of exception is thrown or not.


finally is keyword in java.
finally block is optional in java, we may use it or not.

finally block is not executed in following scenarios >

finally is not executed when System.exit is called.


if in case JVM crashes because of some java.util.Error.

Programming time - we will create following programs to demonstrate finally block in java >

Program 1 to show finally block is executed when exception is not thrown.

Program 2 to show finally block is executed when exception is thrown, in this case catch and finally both blocks are
executed.

Program 3 to show finally block is executed when exception is thrown and not handled properly, in this case catch
blocks does not executes, finally block executes alone.

Program 4 to show finally is not executed when System.exit is called.

Program 5 to show what will happen when catch and finally both return some value.

Program 1 to show finally block is executed when exception is not thrown.

2/5
package finally1;
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class ExceptionTest {
public static void main(String[] args) {

try{
int i=10/1;
}catch(ArithmeticException e){
System.out.println("ArithmeticException handled in catch block");
}
finally{
System.out.println("finally block executed");
}
System.out.println("code after try-catch-finally block");
}
}
/*OUTPUT
finally block executed
code after try-catch-finally block
*/

Program 2 to show finally block is executed when exception is thrown, in this case catch and finally both blocks are
executed.

package finally2;
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class ExceptionTest {
public static void main(String[] args) {

try{
int i=10/0; //will throw ArithmeticException
}catch(ArithmeticException e){
System.out.println("ArithmeticException handled in catch block");
}
finally{
System.out.println("finally block executed");
}
System.out.println("code after try-catch-finally block");
}
}
/*OUTPUT
ArithmeticException handled in catch block
finally block executed
code after try-catch-finally block
*/

Program 3 to show finally block is executed when exception is thrown and not handled properly, in this case catch
blocks does not executes, finally block executes alone.

3/5
package finally3;
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class ExceptionTest {
public static void main(String[] args) {

try{
int i=10/0; //will throw ArithmeticException
}catch(IndexOutOfBoundsException e){
System.out.println("IndexOutOfBoundsException handled in catch block");
}
finally{
System.out.println("finally block executed");
}
System.out.println("code after try-catch-finally block");
}
}
/*OUTPUT
finally block executed
Exception in thread "main" java.lang.ArithmeticException: / by zero
at finally3.ExceptionTest.main(ExceptionTest.java:7)
*/

Its important to note in above program that finally block was executed but catch block didnt because Exception
wasnt handled properly in above program - program throwed ArithmeticException but we were handing
IndexOutOfBoundsException.
Also, sysout statement after try-catch-finally block wasnt executed.

Program 4 to show finally is not executed when System.exit is called.

/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */


public class ExceptionTest {
public static void main(String[] args) {
try{
System.out.println("in try block");
System.exit(0);
}finally{
System.out.println("finally block executed");
}
}
}
/*OUTPUT
in try block
*/

In the above program, finally block is not executed when System.exit is called.

Bit more about System.exit(n) method >

System.exit terminates JVM.


Parameter

4/5
Passing zero as parameter means normal termination &
Passing non-zero as parameter means abnormal termination.

System.exit(n) internally calls Runtime.getRuntime().exit(n)

Program 5 to show what will happen when catch and finally both return some value.
For Program 5, refer this post.

Application of finally block in java programs >

We may use finally block to execute code for database connection closing , because closing connection in try
or catch block may not be safe.

Why closing connection in try block may not be safe?


Because exception may be thrown in try block before reaching connection closing statement.

Why closing connection in catch block may not be safe?


Because inappropriate exception may be thrown in try block and we might not enter catch block to
close connection.

Labels: Core Java Exceptions

5/5
JavaMadeSoEasy.com (JMSE)
www.javamadesoeasy.com /2015/05/throw-exception-in-java.html

You are here : Home / Core Java Tutorials / Exceptions Tutorial in java

Contents of page :

About throw keyword >


throw unchecked exception >
throw checked exception >
If checked Exception is not handled either by try-catch or throws, we will face compilation error.
Program 1- Handling Exception in try-catch block where it was thrown.
Program 2- Handling Exception by throwing it from m() method (using throws keyword) and handling it in try-
catch block from where call to method m() was made.
Program 3- Throwing Exception from m() method and then again throwing it from calling method [ i.e. main
method]

About throw keyword >

throw is a keyword in java.


throw keyword allows us to throw checked or unchecked exception.

throw unchecked exception >

We need not to handle unChecked exception either by catching it or throwing it.

1/4
We throw NullPointerException (unChecked exception) and didnt handled it, no compilation error was thrown.

throw checked exception >

We need to handle checked exception either by catching it, or


throwing it by using throws keyword. (When thrown, exception must be handled in calling environment)

If checked Exception is not handled either by try-catch or throws, we will face compilation error.

Program 1- Handling Exception in try-catch block where it was thrown.

2/4
import java.io.FileNotFoundException;
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class ExceptionTest {
public static void main(String[] args) {
m();
System.out.println("after calling m()");
}
static void m(){
try {
throw new FileNotFoundException();
} catch (FileNotFoundException e) {
System.out.println("FileNotFoundException handled in try-catch block");
}
}
}
/*OUTPUT
FileNotFoundException handled in try-catch block
after calling m()

*/

We throwed FileNotFoundException (checked exception) by using throw keyword and handled it in try-catch block.

Program 2- Handling Exception by throwing it from m() method (using throws keyword) and handling it in try-catch
block from where call to method m() was made.

import java.io.FileNotFoundException;
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class ExceptionTest {
public static void main(String[] args) {
try {
m();
} catch (FileNotFoundException e) {
System.out.println("FileNotFoundException handled in try-catch block");
}
System.out.println("after calling m()");
}
static void m() throws FileNotFoundException{
throw new FileNotFoundException();
}
}
/*OUTPUT
FileNotFoundException handled in try-catch block
after calling m()
*/

method m() propagated exception to calling method (i.e. main method) using throws.

Program 3- Throwing Exception from m() method and then again throwing it from calling method [ i.e. main method]
Ultimately exception is not handled properly in this case, but this approach is used in many live projects (i.e. in web
applications).

3/4
package throwChecked_3_throw_throw;
import java.io.FileNotFoundException;
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class ExceptionTest {
public static void main(String[] args) throws FileNotFoundException {
m();
System.out.println("after calling m()");
}
static void m() throws FileNotFoundException{
throw new FileNotFoundException();
}
}
/*OUTPUT
Exception in thread "main" java.io.FileNotFoundException
at throwChecked_3_throw_throw.ExceptionTest.m(ExceptionTest.java:12)
at throwChecked_3_throw_throw.ExceptionTest.main(ExceptionTest.java:8)
*/

Please note that System.out.println("after calling m()") statement wasn't executed.

method m() propagated exception to calling method (i.e. main method) using throws, and
main propagated exception to JVM using throws.

Differences between throw and throws in java

Labels: Core Java Exceptions

4/4
JavaMadeSoEasy.com (JMSE)
www.javamadesoeasy.com /2015/05/throws-exception-in-java.html

You are here : Home / Core Java Tutorials / Exceptions Tutorial in java

Contents of page :

throws unChecked exception >


throws Checked exception >
Program 1 - Handling Exception by throwing it from m() method (using throws keyword) and handling it in try-
catch block from where call to method m() was made.
Program 2 - Throwing Exception from m() method and then again throwing it from calling method [ i.e. main
method]

throws is written in methods definition to indicate that method can throw exception.

throws unChecked exception >

We need not to handle unChecked exception either by catching it or throwing it.

Above code throws NullPointerException (unChecked exception) and didnt handled it from where method m() was
called and no compilation error was thrown.

throws Checked exception >

We need to handle checked exception either by catching it or throwing it further, if not handled we will face
compilation error.

1/3
Program 1 - Handling Exception by throwing it from m() method (using throws keyword) and handling it in try-catch
block from where call to method m() was made.

import java.io.FileNotFoundException;
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class ExceptionTest {
public static void main(String[] args) {
try {
m();
} catch (FileNotFoundException e) {
System.out.println("FileNotFoundException handled in try-catch block");
}
System.out.println("after calling m()");
}
static void m() throws FileNotFoundException{

}
}
/*OUTPUT
after calling m()
*/

method m() propagated exception to calling method (i.e. main method) using throws.

Program 2 - Throwing Exception from m() method and then again throwing it from calling method [ i.e. main method]
Ultimately exception is not handled properly in this case, but this approach is used in many live projects (i.e. in web
applications).

2/3
import java.io.FileNotFoundException;
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class ExceptionTest {
public static void main(String[] args) throws FileNotFoundException {
m();
System.out.println("after calling m()");
}
static void m() throws FileNotFoundException{

}
}
/*OUTPUT
after calling m()

*/

method m() propagated exception to calling method (i.e. main method) using throws, and
main propagated exception to JVM using throws.

Labels: Core Java Exceptions

3/3
Nested try-catch block in java
www.javamadesoeasy.com /2015/05/nested-try-catch-block-in-java.html

You are here : Home / Core Java Tutorials / Exceptions Tutorial in java

Java exception handling allows us to use nested try-catch block.

Nested try-catch block means using try-catch block inside another try-catch block.

/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */


public class ExceptionTest {
public static void main(String[] args) {

try{
int i=10/0; //will throw ArithmeticException
}catch(ArithmeticException ae){
System.out.println("try-catch block handled - ArithmeticException" );

//using nested try-catch block


try{
String s=null;
s.charAt(0); //will throw NullPointerException
}catch(NullPointerException npe){
System.out.println("NESTED try-catch block handled - "
+ "NullPointerException");
}

}
}
}
/*OUTPUT
try-catch block handled - ArithmeticException
NESTED try-catch block handled - NullPointerException
*/

Labels: Core Java Exceptions

1/1
Multiple catch block in java
www.javamadesoeasy.com /2015/05/multiple-catch-block-in-java.html

You are here : Home / Core Java Tutorials / Exceptions Tutorial in java

Java exception handling allows us to use multiple catch block.

Important Point about multiple catch block >

1. Exception class handled in starting catch block must be subclass of Exception class handled in following
catch blocks (otherwise we will face compilation error).
2. Either one of the multiple catch block will handle exception at time.

Here is the syntax for writing multiple catch block >

try{
//code . . . . .
}catch(IOException ex1){
//code . . . . .
} catch(SQLException ex2){
//code . . . . .
}

Program - Lets understand the concept of multiple catch block>

/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */


public class ExceptionTest {
public static void main(String[] args) {

try{
int i=10/0; //will throw ArithmeticException
}catch(ArithmeticException ae){
System.out.println("Exception handled - ArithmeticException" );
}catch(RuntimeException re){
System.out.println("Exception handled - RuntimeException");
}catch(Exception e){
System.out.println("Exception handled - Exception");
}
}
}
/*OUTPUT
Exception handled - ArithmeticException
*/

1/2
In the above above >
ArithmeticException has been used in first catch block
RuntimeException has been used in second catch block
Exception has been used in third catch block

Exception is superclass of RuntimeException and


RuntimeException is superclass of ArithmeticException.

Now, what will happen if RuntimeException is used in first catch and ArithmeticException is used in second catch
block.
If RuntimeException would have been used in first catch and ArithmeticException in second catch block then
compile time error would have occurred Unreachable catch block for ArithmeticException. It is already handled by
the catch block for RuntimeException
because in first catch block superclass RunTimeException can handle ArithmeticException, hence making second
catch block (i.e. with ArithmeticException) unreachable.

Above code snippet shows compilation error.

Why shouldnt you use Exception for catching all exceptions in java?
Catching Exception rather than handling specific exception can be vulnerable to our application. Multiple catch
blocks must be used to catch specific exceptions, because handling specific exception gives developer the liberty of
taking appropriate action and develop robust application.

Labels: Core Java Exceptions

2/2
What will happen when catch and finally block both return
value, also when try and finally both return value in java
www.javamadesoeasy.com /2015/05/what-will-happen-when-catch-and-finally.html

You are here : Home / Core Java Tutorials / Exceptions Tutorial in java

When catch and finally block both return value, method will ultimately return value returned by finally block
irrespective of value returned by catch block.

/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */


public class ExceptionTest {
public static void main(String[] args) {
System.out.println("method return -> " +m());
}

static String m(){


try{
int i=10/0; //will throw ArithmeticException
}catch(ArithmeticException e){
return "catch";
}finally{
return "finally";
}

}
}
/*OUTPUT
method return -> finally
*/

In above program, i=10/0 will throw ArithmeticException and enter catch block to return "catch", but ultimately
control will enter finally block to return "finally".

When try and finally block both return value, method will ultimately return value returned by finally block irrespective
of value returned by try block.

1/2
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class ExceptionTest {
public static void main(String[] args) {
System.out.println("method return -> " +m());
}

static String m(){


try{
int i=1;
return "try";
}finally{
return "finally";
}

}
}
/*OUTPUT
method return -> finally
*/

In above program, try block will "try", but ultimately control will enter finally block to return "finally".

2/2
Creating User defined checked and unchecked Exception/
custom Exception in java
www.javamadesoeasy.com /2015/05/creating-user-defined-checked-and.html

You are here : Home / Core Java Tutorials / Exceptions Tutorial in java

Creating user defined checked exception >

class UserDefinedException extends Exception {


UserDefinedException(String s) {
super(s);
}
}

By extending java.lang.Exception, we can create checked exception.

Creating user defined unchecked exception >

class UserDefinedException extends RuntimeException {


UserDefinedException(String s) {
super(s);
}
}

By extending java.lang.RuntimeException, we can create unchecked exception.

Full program for testing user defined checked Exception >

1/2
package com.ankit;
/*
* User defined Exception/ custom Exception
*/
class UserDefinedException extends Exception {
UserDefinedException(String s) {
super(s);
}
}
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com
* Main class */
public class UserDefinedExceptionTest {
public static void main(String... arg) {
try {
throw new UserDefinedException("user defined exception was thrown "
+ "and handled.");
} catch (UserDefinedException e) {
e.printStackTrace();
}
}
}
/*OUTPUT
com.ankit.UserDefinedException: user defined exception was thrown and handled.
at com.ankit.UserDefinedExceptionTest.main(UserDefinedExceptionTest.java:25)
*/

Labels: Core Java Exceptions

2/2
Catch block and Automatic Resource Management in java 7
www.javamadesoeasy.com /2015/05/catch-block-and-automatic-resource.html

You are here : Home / Core Java Tutorials / Exceptions Tutorial in java

Contents of page :

Features of multi catch syntax >


Using multi catch syntax to catch subclass and its superclass exception.

As we read in previous posts java allows us to handle multiple exceptions by using multiple catch blocks.
In that post we read Exception class handled in starting catch block must be subclass of Exception class handled in
following catch blocks (otherwise we will face compilation error).
Now, java 7 has done improvements in multiple exception handling by introducing multi catch syntax which helps in
automatic resource management.

Features of multi catch syntax >

Has improved way of catching multiple exceptions.


This syntax does not looks clumsy.
Reduces developer efforts of writing multiple catch blocks.
Allows us to catch more than one exception in one catch block.
Helps in automatic resource management.

Here is the multi catch syntax >

try{
//code . . . . .
}catch(IOException | SQLException ex){
//code . . . . .
}

We could separate different exceptions using pipe ( | )

Before java 7, for catching IOException and SQLException we were needed to write two catch block like this >

1/4
But in java 7, we can catch IOException and SQLException in one catch block using multi catch syntax like this >

2/4
Using multi catch syntax to catch subclass and its superclass exception.
When multiple catch blocks are used , first catch block could be subclass of Exception class handled in following
catch blocks like this >
IOException is subclass of Exception.

But in java 7, if multi catch syntax is used to catch subclass and its superclass than compilation error will be thrown.
IOException and Exception in multi catch syntax will cause compilation error The exception IOException is already
caught by the alternative Exception.
IOException is subclass of Exception.

Solution >
We must use only Exception to catch its subclass like this >

3/4
4/4
Try-with-resources in java - java.lang.AutoCloseable
interface - java7
www.javamadesoeasy.com /2015/05/try-with-resources-in-java.html

You are here : Home / Core Java Tutorials / Exceptions Tutorial in java

Before java 7, we used to write explicit code for closing file in finally block by using try-finally block like this >

/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */


public class TryWithResourseTest {
public static void main(String[] args) throws IOException {
InputStream inputStream = null;
try{
inputStream = new FileInputStream("c:/txtFile.txt");
//code......
}finally{
if(inputStream!=null)
inputStream.close();
}
}
}

In java 7, using Try-with-resources >

we need not to write explicit code for closing file.

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class TryWithResourseTest {
public static void main(String[] args) throws IOException {
try (InputStream inputStream = new FileInputStream("c:/txtFile.txt")) {
//code...
}
}
}

Note : Above program will execute properly provided file is found at specified directory.

Now, question comes why we need not to close file when we are using Try-with-resources?
Because FileInputStream implements java.lang.AutoCloseable interface (AutoCloseable interfaces close method
automatically closes resources which are no longer needed.)

Which classes can be used inside Try-with-resources?


All the classes which implements AutoCloseable interface can be used inside Try-with-resources.

1/2
Using multiple resources inside Try-with-resources >
Try-with-resources allows us to use multiple resources inside it, all that we need to do is separate resources by
semicolon (;)

/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */


public class TryWithResourseTest {
public static void main(String[] args) throws IOException {
try (InputStream inputStream = new FileInputStream("c:/txtFile.txt") ;
InputStream bInputStream = new BufferedInputStream(inputStream) ){
//code...
}
}
}

Note : Above program will execute properly provided file is found at specified directory.

2/2
Exception propagation in java - deep understanding of how
checked and unchecked exceptions are propagated
www.javamadesoeasy.com /2015/05/exception-propagation-in-java-deep.html

You are here : Home / Core Java Tutorials / Exceptions Tutorial in java

Contents of page :

Exception Propagation >


Propagating unchecked exception (NullPointerException) >
Let's see how stack of methods is formed >
Propagating checked exception (FileNotFoundException) using throws keyword>

Hi! In this post ill be explaining you in detail how checked and unchecked exceptions are propagated in java.

Exception Propagation >


Whenever methods are called stack is formed and an exception is first thrown from the top of the stack and if it is not
caught, it starts coming down the stack to previous methods until it is not caught.
If exception remains uncaught even after reaching bottom of the stack it is propagated to JVM and program is
terminated.

Propagating unchecked exception (NullPointerException) >


unchecked exceptions are automatically propagated in java.

1/4
Now, ill be explaining you how unchecked exception was propagated.
Lets see step by step what happened in above program >

JVM called main method


step 1 - main called method1()
step 2 - method1 called method2()
step 3 - method2 called method3()
step 4 - method3 automatically propagated exception to method2() [because, unchecked exceptions are
propagated automatically]
step 5 - method2 automatically propagated exception to method1() [because, unchecked exceptions are
propagated automatically]
step 6 - method2 automatically propagated exception to main() [because, unchecked exceptions are
propagated automatically]
main() automatically propagated exception to JVM [because, unchecked exceptions are propagated
automatically]

Let's see how stack of methods is formed >

2/4
In the above program, stack is formed and an exception is first thrown
from the top of the stack [ method3() ] and it remains uncaught there,
and starts coming down the stack to previous methods to method2(),
then to method1(), than to main() and it remains uncaught throughout.
exception remains uncaught even after reaching bottom of the stack [
main() ] so it is propagated to JVM and ultimately program is terminated
by throwing exception [ as shown in output ].

Propagating checked exception (FileNotFoundException) using throws


keyword >
For propagating checked exceptions method must throw exception by
using throws keyword.

Now, ill be explaining you how checked exception was propagated.


Lets see step by step what happened in above program >

JVM called main method


step 1 - main called method1()
step 2 - method1 called method2()
step 3 - method2 called method3()

3/4
step 4 - method3 propagated exception to method2() using throws keyword.[because, checked exceptions
are not propagated automatically]
step 5 - method2 propagated exception to method1() using throws keyword.[because, checked exceptions
are not propagated automatically]
step 6 - method2 propagated exception to main() using throws keyword.[because, checked exceptions are
not propagated automatically]
main() propagated exception to JVM using throws keyword.[because, checked exceptions are not
propagated automatically]

/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */

4/4
Method overloading in java - in detail with programs,10
Features,need of method overloading, overloading main
method, Diagram and tabular form of Implicit
casting/promotion of primitive Data type, compile time
polymorphism
www.javamadesoeasy.com /2015/06/method-overloading-in-java-in-detail.html

You are here : Home / Core Java Tutorials / Core Java tutorial in detail

Contents of page :

Method overloading >

Advantage of method overloading -

Method overloading can be done by -


(Method definition formation) Lets understand method overloading by diagram -
Features of Method overloading -
Program 1 - to overload methods by changing number of arguments.
Program 2 - to overload methods by keeping same number of arguments but changing data data type of
arguments
Program 3 - Method overloading in SubClass
Program 4 - overloading main method in java
Implicit casting/promotion of primitive Data type in java >

Diagram of Implicit casting/promotion of primitive Data type in java >


Tabular form Implicit casting/promotion of primitive Data type in java >

Now, lets create programs to understand Implicit Data type casting/ promotion of primitive data types in java with
method overloading in java >

Program 5.1 -

In the program, 2 is a int, 2 can be casted to double as well , but rather than casting compiler will
call method with int as argument.

Program 5.2 -

In the program, 2 is a int, 2 can be casted to double and float as well, but rather than casting to
double compiler will cast 2 to float and call method with float as argument.

Program 5.3 -

In the program, 2 is a int, 2 can be casted to double but cannot be casted to short, compiler will
cast 2 to double and call method with double as argument.
1/9
Data types are not demoted Implicitly, though they may be demoted explicitly, which may cause data
loss.

Example Program 6 - If we want to demote double to int, we will have to add explicit cast. In explicit cast we
lost decimal value of 2.2 and are left with 2

Method overloading >


When a class have same method name with different argument, than it is called method overloading.

Advantage of method overloading -


Method overloading enables consistency in the naming of methods which logically perform almost similar tasks and
the only difference is in number of arguments. Method overloading enables same method name to be reused in
program.
Method overloading is done to make program logically more readable and understandable.

Example -

/*
* Method to calculate sum of 2 arguments
*/
public void sum(int x, int y) {
System.out.println("sum of 2 arguments = "+ (x+y));
}
/*
* Method to calculate sum of 3 arguments
*/
public void sum(int x, int y, int z) {
System.out.println("sum of 3 arguments = "+ (x+y+z));
}

sum() method logically perform almost similar tasks and the only difference is in number of arguments. Method
overloading enables same method name sum() to be reused in program.

Method overloading can be done by -

1. changing number of arguments, or (In Program 1 below)


2. keeping same number of arguments but changing data data type of arguments. (In Program 2 below)

(Method definition formation) Lets understand method overloading by diagram -


Method definition is formed by using following 5 terms -

2/9
1. Access modifier - Does not matter.

2. Return type - Does not matter.

3. Method name - same method name.

4. Number of parameters in java - different number of parameters

5. Exception thrown - Does not matter.

10 Features of Method overloading -

1. Call to overloaded method is bonded at compile time.

2. Method overloading concept is also known as compile time polymorphism in java.

3. Java does not allow overloading by changing the return type, though overloaded methods can change the
return type.

4. Method overloading is generally done in same class but can also be done in SubClass (In Program 3 below)

5. private methods can be overloaded in java.

3/9
6. final methods can be overloaded in java.

7. Main method can also be overloaded in java (In Program 4 below)

8. Both Static and instance method can be overloaded in java. (In Program 1 below, we have overloaded
instance method, likewise we could also overload static method)

Program 1 - to overload methods by changing number of arguments.

/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */


public class MyClass {
/*
* Method to calculate sum of 2 arguments
*/
public void sum(int x, int y) {
System.out.println("sum of 2 arguments = "+ (x+y));
}
/*
* Method to calculate sum of 3 arguments
*/
public void sum(int x, int y, int z) {
System.out.println("sum of 3 arguments = "+ (x+y+z));
}
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.sum(2, 3); // will call method to calculate sum of 2 arguments
obj.sum(2, 4, 3); // will call method to calculate sum of 3 arguments
}
}
/*OUTPUT
sum of 2 arguments = 5
sum of 3 arguments = 9
*/

Program 2 - to overload methods by keeping same number of arguments but changing data data type of arguments

4/9
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class MyClass {
/*
* Method to calculate sum of 2 int type arguments
*/
public void sum(int x, int y) {
System.out.println("sum of 2 int type arguments = "+ (x+y));
}
/*
* Method to calculate sum of 2 double type arguments
*/
public void sum(double x, double y) {
System.out.println("sum of 2 double type arguments = "+ (x+y));
}
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.sum(2, 3); // will call method to calculate sum of 2 int type arguments
obj.sum(1.2, 2.3); // will call method to calculate sum of 2 double type arguments
}
}
/*OUTPUT
sum of 2 int type arguments = 5
sum of 2 double type arguments = 3.5
*/

Program 3 - Method overloading in SubClass

class SuperClass{
public void sum(int x, int y) {
System.out.println("sum of 2 int type arguments = "+ (x+y));
}
}
class SubClass extends SuperClass{
public void sum(double x, double y) {
System.out.println("sum of 2 double type arguments = "+ (x+y));
}
}
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class MyClass {
public static void main(String[] args) {
SubClass obj = new SubClass();
obj.sum(2, 1);
obj.sum(2.1, 3.4);
}
}
/*OUTPUT
sum of 2 int type arguments = 3
sum of 2 double type arguments = 5.5
*/

In the above program, method with 2 double type arguments of SubClass overloaded method with 2 double type
arguments of SuperClass.

5/9
Program 4 - overloading main method in java

/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */


public class MyClass {
public static void main(String[] args) {
System.out.println("main(String[] args)");
main();
}
public static void main(){
System.out.println("main()");
}
}
/*OUTPUT
main(String[] args)
main()
*/

When JVM loads MyClass it finds out main method with signature = [ public static void main(String[] args)].

Implicit casting/promotion of primitive Data type in java >


Its very important from ocjp exam point of view.

Diagram of Implicit casting/promotion of primitive Data type in java >

Tabular form Implicit casting/promotion of primitive Data type in java >

Primitive Data type Can be implicitly casted/promoted to

byte short, int, long, float, double

short int, long, float, double

6/9
char int, long, float, double

int long, float, double

long float, double

float double

Now, lets create programs to understand Implicit Data type casting/ promotion of primitive data types in java with
method overloading in java >

Program 5.1 -
In the program, 2 is a int, 2 can be casted to double as well , but rather than casting compiler will call method with int
as argument.

/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */


public class MyClass {
static void m(double x) {
System.out.println("double");
}
static void m(int x) {
System.out.println("int");
}

public static void main(String args[]) {


m(2);
}
}
/*OUTPUT
int
*/

Program 5.2 -
In the program, 2 is a int, 2 can be casted to double and float as well, but rather than casting to double compiler will
cast 2 to float and call method with float as argument.

public class MyClass {


static void m(double x) {
System.out.println("double");
}
static void m(float x) {
System.out.println("float");
}

public static void main(String args[]) {


m(2);
}
}
/*OUTPUT
float
*/
7/9
When an exact match is not found for parameter then compiler finds the method with the smallest argument that is
wider than the parameter. This concept is also known as widening of data type.
Example - In the above program, an exact match is not found for parameter (int) then compiler finds the method with
the smallest argument (float rather than double) that is wider than the parameter(int). int is widened to float.

Program 5.3 -
In the program, 2 is a int, 2 can be casted to double but cannot be casted to short, compiler will cast 2 to double and
call method with double as argument.

public class MyClass {


static void m(double x) {
System.out.println("double");
}
static void m(short x) {
System.out.println("short");
}

public static void main(String args[]) {


m(2);
}
}
/*OUTPUT
double
*/

In the above program, int is widened to double.

Program 5.3 -
In the program, 2 is a int, 2 cant be casted to either short or byte, so we will face compilation error

public class MyClass {


static void m(byte x) {
System.out.println("double");
}
static void m(short x) {
System.out.println("short");
}

public static void main(String args[]) {


m(2); //compilation error
}
}
/*OUTPUT
*/

Data types are not demoted Implicitly, though they may be demoted explicitly, which may cause data loss.

Example Program 6 - If we want to demote double to int, we will have to add explicit cast. In explicit cast we lost
8/9
decimal value of 2.2 and are left with 2

public class MyClass {


public static void main(String args[]) {
double d=2.2;
int i=(int) d;
System.out.println(i);
}
}
/*OUTPUT
2
*/

9/9
Throw/declare checked and unchecked exception while
overriding superclass method in java
www.javamadesoeasy.com /2015/05/throwdeclare-checked-and-unchecked.html

You are here : Home / Core Java Tutorials / Exceptions Tutorial in java

Contents of page :

If superclass method does not throw/declare any exception >


If superclass method throws/declare checked/compileTime exception >
If superclass method throws/declare unchecked/RuntimeException >

PROGRAMMING TIME >


If superclass method does not throw/declare any exception >

Program1 to show - overridden method of subclass can declare/throw any unchecked


/RuntimeException (superclass or subclass)
Program2 to show - overridden method of subclass cannot declare/throw any checked exception

If superclass method throws/declare checked/compileTime exception >

Program3 to show - overridden method of subclass can declare/throw narrower (subclass of) checked
exception
Program4 to show - overridden method of subclass cannot declare/throw broader (superclass of)
checked exception
Program5 to show - overridden method of subclass can declare/throw any unchecked
/RuntimeException

If superclass method throws/declare unchecked/RuntimeException >

Program6 to show - overridden method of subclass can declare/throw any unchecked


/RuntimeException
Program7 to show - overridden method of subclass cannot declare/throw any checked exception

Newly added programs in article >


If superclass method does not throw/declare any exception >

overridden method of subclass may not declare/throw any exception (As shown in Program 8 - Newly added
on reader's request -).

If superclass method throws/declare checked/compileTime exception >

overridden method of subclass may not declare/throw any exception. (As shown in Program 9 - Newly added
1/9
on reader's request).

If superclass method throws/declare unchecked/RuntimeException >

overridden method of subclass may not declare/throw any exception (As shown in Program 10 - Newly added
on reader's request - so as to avoid any confusion in understanding of basic concepts) .

In this post well explore different possibilities of how we can handle checked and unchecked exception while
overriding superclass method.

If superclass method does not throw/declare any exception >

overridden method of subclass can declare/throw any unchecked /RuntimeException (As shown in
Program1), or
overridden method of subclass cannot declare/throw any checked exception (As shown in Program2), or
overridden method of subclass may not declare/throw any exception (As shown in Program 8 - Newly added
on reader's request - so as to avoid any confusion in understanding of basic concepts) ..

If superclass method throws/declare checked/compileTime exception >

overridden method of subclass can declare/throw narrower (subclass of) checked exception (As shown in
Program3), or
overridden method of subclass cannot declare/throw broader (superclass of) checked exception (As shown in
Program4), or
overridden method of subclass can declare/throw any unchecked /RuntimeException (As shown in
Program5), or
overridden method of subclass can declare/throw same exception, or
overridden method of subclass may not declare/throw any exception. (As shown in Program 9 - Newly added
on reader's request - so as to avoid any confusion in understanding of basic concepts) .

If superclass method throws/declare unchecked/RuntimeException >

overridden method of subclass can declare/throw any unchecked /RuntimeException (superclass or


subclass) (As shown in Program1), or
overridden method of subclass cannot declare/throw any checked exception (As shown in Program2), or
overridden method of subclass can declare/throw same exception, or
overridden method of subclass may not declare/throw any exception (As shown in Program 10 - Newly added
on reader's request - so as to avoid any confusion in understanding of basic concepts) .

PROGRAMMING TIME >

2/9
------ If superclass method does not throw/declare any exception >

Program1 to show - overridden method of subclass can declare/throw any unchecked /RuntimeException
(superclass or subclass)

If superclass method does not throw/declare any exception - overridden method of subclass can declare/throw any
unchecked /RuntimeException (superclass or subclass)

class SuperClass{
void method(){
System.out.println("superClass method");
}
}
class SubClass extends SuperClass{
void method() throws NullPointerException{
System.out.println("SubClass method");
}
}
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com
* Main class */
public class ExceptionTest {
public static void main(String[] args) throws Exception {
SuperClass obj=new SubClass();
obj.method();
}
}
/*OUTPUT
SubClass method
*/

Program2 to show - overridden method of subclass cannot declare/throw any checked exception

If superclass method does not throw/declare any exception - overridden method of subclass cannot declare/throw
any checked exception

Any attempt to throw checked exception in overridden method of subclass will cause compilation error.

3/9
----If superclass method throws/declare checked/compileTime exception >

Program3 to show - overridden method of subclass can declare/throw narrower (subclass of) checked exception

If superclass method throws/declare checked/compileTime exception - overridden method of subclass can


declare/throw narrower (subclass of) checked exception

IOException is superclass of FileNotFoundException.

import java.io.FileNotFoundException;
import java.io.IOException;
class SuperClass{
void method() throws IOException{
System.out.println("superClass method");
}
}
class SubClass extends SuperClass{
void method() throws FileNotFoundException{
System.out.println("SubClass method");
}
}
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com
* Main class */
public class ExceptionTest {
public static void main(String[] args) throws Exception {
SuperClass obj=new SubClass();
obj.method();
}
}
/*OUTPUT
SubClass method
*/

Program4 to show - overridden method of subclass cannot declare/throw broader (superclass of) checked exception

If superclass method throws/declare checked/compileTime exception - overridden method of subclass cannot


declare/throw broader (superclass of) checked exception

Any attempt to throw broader (superclass of) checked exception in overridden method of subclass will cause
compilation error.
Exception is superclass of IOException.

4/9
Program5 to show - overridden method of subclass can declare/throw any unchecked /RuntimeException

If superclass method throws/declare checked/compileTime exception - overridden method of subclass can


declare/throw any unchecked /RuntimeException

import java.io.IOException;
class SuperClass{
void method() throws IOException{
System.out.println("superClass method");
}
}
class SubClass extends SuperClass{
void method() throws NullPointerException{
System.out.println("SubClass method");
}
}
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com
* Main class */
public class ExceptionTest {
public static void main(String[] args) throws Exception {
SuperClass obj=new SubClass();
obj.method();
}
}
/*OUTPUT
SubClass method
*/

--------If superclass method throws/declare unchecked/RuntimeException >

Program6 to show - overridden method of subclass can declare/throw any unchecked /RuntimeException

If superclass method throws/declare unchecked/RuntimeException - overridden method of subclass can


declare/throw any unchecked /RuntimeException

RuntimeException is superclass of NullPointerException.

5/9
class SuperClass{
void method() throws NullPointerException{
System.out.println("superClass method");
}
}
class SubClass extends SuperClass{
void method() throws RuntimeException{
System.out.println("SubClass method");
}
}
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com
* Main class */
public class ExceptionTest {
public static void main(String[] args) {
SuperClass obj=new SubClass();
obj.method();
}
}
/*OUTPUT
SubClass method
*/

Program7 to show - overridden method of subclass cannot declare/throw any checked exception

If superclass method throws/declare unchecked/RuntimeException - overridden method of subclass cannot


declare/throw any checked exception

Any attempt to throw checked exception in overridden method of subclass will cause compilation error.

Lets see newly added programs >

If superclass method does not throw/declare any exception >

overridden method of subclass may not declare/throw any exception (As shown in Program 8 - Newly added

6/9
on reader's request - so as to avoid any confusion in understanding of basic concepts) ..

class SuperClass{
void method(){
System.out.println("superClass method");
}
}
class SubClass extends SuperClass{
void method() {
System.out.println("SubClass method");
}
}
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com
* Main class */
public class ExceptionTest {
public static void main(String[] args) throws Exception {
SuperClass obj=new SubClass();
obj.method();
}
}
/*OUTPUT
SubClass method
*/

Its a valid method overriding program.

If superclass method throws/declare checked/compileTime exception >

overridden method of subclass may not declare/throw any exception. (As shown in Program 9 - Newly added
on reader's request - so as to avoid any confusion in understanding of basic concepts) .

7/9
import java.io.FileNotFoundException;
import java.io.IOException;
class SuperClass{
void method() throws IOException{
System.out.println("superClass method");
}
}
class SubClass extends SuperClass{
void method(){
System.out.println("SubClass method");
}
}
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com
* Main class */
public class ExceptionTest {
public static void main(String[] args) throws Exception {
SuperClass obj=new SubClass();
obj.method();
}
}
/*OUTPUT
SubClass method
*/

Its a valid method overriding program.

If superclass method throws/declare unchecked/RuntimeException >

overridden method of subclass may not declare/throw any exception (As shown in Program 10 - Newly added
on reader's request - so as to avoid any confusion in understanding of basic concepts) .

8/9
class SuperClass{
void method() throws NullPointerException{
System.out.println("superClass method");
}
}
class SubClass extends SuperClass{
void method(){
System.out.println("SubClass method");
}
}
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com
* Main class */
public class ExceptionTest {
public static void main(String[] args) {
SuperClass obj=new SubClass();
obj.method();
}
}
/*OUTPUT
SubClass method
*/

Its a valid method overriding program.

Having any doubt? or you you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.

9/9
Method overloading on basis of exceptions in java
www.javamadesoeasy.com /2015/05/method-overloading-on-basis-of.html

You are here : Home / Core Java Tutorials / Exceptions Tutorial in java

In this post we will learn how method can be overloaded on basis of exceptions.

But now question which overloaded exception will be called.

Lets take an example :

Ques. Let's say one method handles Exception and other handles ArithmeticException. Which method will be
invoked when ArithmeticException is thrown?

Ans. Method which handles more specific exception will be called.

Program >

import java.io.IOException;
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com
* Main class */
public class ExceptionTest {

void method(Exception e){


System.out.println(e+" caught in Exception method");
}
void method(ArithmeticException ae){
System.out.println(ae+" caught in ArithmeticException method" );
}

public static void main(String[] args) {


ExceptionTest obj=new ExceptionTest();
obj.method(new ArithmeticException());
obj.method(new IOException());
}
}
/* OUTPUT
java.lang.ArithmeticException caught in ArithmeticException method
java.io.IOException caught in Exception method
*/

1/1
12 Exception handling best practices and guidelines for
using exceptions in java
www.javamadesoeasy.com /2015/05/exception-handling-best-practices-and.html

You are here : Home / Core Java Tutorials / Exceptions Tutorial in java

By handling exceptions we end up giving some meaningful message to end user rather than giving meaningless
message.

Exception handling best practices and guidelines for using exceptions in java -

1. Throw exceptions when the method cannot handle the exception, and more importantly, must be handled by
the caller.

Example -
In Servlets - doGet() and doPost() throw ServletException or IOException in certain circumstances where the
request could not be read correctly. Neither of these methods are in a position to handle the exception, but the
container is (which generally results in the 404 error page in most cases).

2. Bubble the exception if the method cannot handle it. This is a corollary of the above point, but applicable to
methods that must catch the exception. If the caught exception cannot be handled correctly by the method,
then it is preferable to bubble it.

3. Throw the exception right away. If an exception scenario is encountered, then it is a good practice to throw
an exception indicating the original point of failure, instead of attempting to handle the failure via error codes,
until a point deemed suitable for throwing the exception. In other words, attempt to minimize mixing exception
handling with error handling.

4. Either log the exception or bubble it, but don't do both. Logging an exception often indicates that the
exception stack has been completely unwound, indicating that no further bubbling of the exception has
occurred. Hence, it is not recommended to do both at the same time, as it often leads to a frustrating
experience in debugging.

5. Application should not try to catch Error - Because, in most of cases recovery from an Error is almost
impossible. So, application must be allowed to terminate.

Example>
Lets say errors like OutOfMemoryError and StackOverflowError occur and are caught then JVM might not be able
to free up memory for rest of application to execute, so it will be better if application dont catch these errors and is
allowed to terminate.

6. Use subclasses of checked exceptions, when you except the caller to handle the exception. This results in
the compiler throwing an error message if the caller does not handle the exception. Beware though, this
usually results in developers "swallowing" exceptions in code.
1/2
7. Throwing RuntimeException - We must avoid throwing Runtime exceptions because they generally indicate
programming errors.

8. Use exception class hierarchies for communicating information about exceptions across various tiers. By
implementing a hierarchy, you could generalize the exception handling behavior in the caller. For example,
you could use a root exception like DomainException which has several subclasses like
InvalidCustomerException, InvalidProductException etc. The caveat here is that your exception hierarchy can
explode very quickly if you represent each separate exceptional scenario as a separate exception.

9. Avoid catching exceptions you cannot handle. Pretty obvious, but a lot of developers attempt to catch
java.lang.Exception or java.lang.Throwable. Since all subclassed exceptions can be caught, the runtime
behavior of the application can often be vague when "global" exception classes are caught. After all, one
wouldn't want to catch OutOfMemoryError - how should one handle such an exception?

10. Wrap exceptions with care. Rethrowing an exception resets the exception stack. Unless the original cause
has been provided to the new exception object, it is lost forever. In order to preserve the exception stack, one
will have to provide the original exception object to the new exception's constructor.

11. Convert checked exceptions into unchecked ones only when required. When wrapping an exception, it is
possible to wrap a checked exception and throw an unchecked one (User defined unchecked Exception).
This is useful in certain cases, especially when the intention is to stop the currently executing thread.
However, in other scenarios this can cause a bit of pain, for the compiler checks are not performed.
Therefore, adapting a checked exception as an unchecked one is not meant to be done blindly.

12. Throwable should be caught (This might be contrary to few above mentioned points, but could be useful in
certain scenarios) - rollback transactions which went wrong, if any (may be database transactions) and once
transactions have been successfully rolled back we must rethrow Throwable.

What we should do when we are unable to handle specific exception ?


Lets say we have handled NullPointerException in code and at runtime ArithmeticException is thrown, then rather
than showing ArithmeticException to user we must show him some meaningful exception and must catch
ArithmeticException in its superclass Exception and log it for further analyzation.

2/2
How to handle exception thrown from static block in java?
Why throw not allowed in static block
www.javamadesoeasy.com /2015/12/how-to-handle-exception-thrown-from.html

You are here : Home / Core Java Tutorials / Exceptions Tutorial in java
How to handle exception or error thrown from static block or initializing static variable in java?
Why throw not allowed in static block in java?
Java does not allows static initialization block to throw any exception, though it is allowed to use use try-catch block
inside static initialization block.

First of all I will like to discuss about what are static blocks in java? what are features of static block in java?

static blocks are called as soon as class is loaded even before instance of class is created (i.e. before
constructor is called)
static blocks executes before instance blocks. Read Differences between Instance initialization block and
Static initialization block in java .

static block are also known as static initialization blocks in java.


Any code written inside static block is thread safe.
Only static variables can be accessed inside static block
static blocks can be used for initializing static variables or calling any static method.
this keyword cannot be used in static block.

Why throw not allowed in static block?


We dont have any control over the execution of static blocks because they are executed when class is loaded.
We cannot call static block at our will i.e. after class has been loaded or in between program execution. So, throwing
exception from static initialization block does not make any sense.

How to handle exception or error thrown from static block or initializing static variable in java?
If any RuntimeException occurs in static initialization block of class then java.lang.ExceptionInInitializerError is
thrown. So, we can catch ExceptionInInitializerError and handle exception thrown from static block in java.
We will create simple program to understand how RuntimeException occured in static initialization block of class
can throw ExceptionInInitializerError and how to handle it.

1/3
public class SolveStaticBlockExceptionExample {
public static void main(String[] args) {
try {
new A(); // It will throw java.lang.ExceptionInInitializerError
} catch (Throwable error) {
error.printStackTrace();
}
}
}
class A {
static { // static block of class, which will throw RuntimeException
System.out.println("In static block of class A" );
System.out.println(1 / 0); // It will throw java.lang.ArithmeticException
}
/* Constructor of class A will never get executed */
A() {
System.out.println("In constructor of class A" );
}
}

Output of above program >

In static block of class A


java.lang.ExceptionInInitializerError
at SolveStaticBlockExceptionExample.main(SolveStaticBlockExceptionExample.java:4)
Caused by: java.lang.ArithmeticException: / by zero
at A.<clinit>(SolveStaticBlockExceptionExample.java:14)
... 1 more

In the above program, first new A() at line 4 throwed ExceptionInInitializerError because ArithmeticException
occurred in initializing the class (i.e. in static initialization block of class).

You must read ArithmeticException is an unchecked exception and it is propagated automatically in java.

What static initialization blocks allows regarding Exceptions in java?

Java allows to use use try-catch block inside static initialization block.

If any RuntimeException (Example - ArithmeticException by using 1/0) is thrown it is propagated


automatically in java.

What static initialization blocks doesnt allows?


2/3
Java does not allows static initialization block to throw any exception in java.

Explicitly it does not allow you to throw even RuntimeException . Example - throw new RuntimeException() is
not allowed.

throw and throws both are not allowed in static initialization block.

3/3
Differences between Exception and Error in java
www.javamadesoeasy.com /2015/05/differences-between-exception-and-error.html

You are here : Home / Core Java Tutorials / Exceptions Tutorial in java

In this post we will be discussing differences between java.lang.Exception and java.lang.Error

Differences between Exception and Error in java >

Property Exception Error

1 serious Exception does not indicate any serious Error indicates some serious problems that
problem? problem. our application should not try to catch.

2 divided into Exception are divided into checked and Error are not divided further into such
checked and unchecked exceptions. classifications.
unchecked

3 Which The class Exception and all its Error and its subclasses are regarded as
classes are subclasses that are not also subclasses unchecked exceptions
which type of of RuntimeException are checked
exception? exceptions.
either
checked or The class RuntimeException and all its
unchecked subclasses are unchecked exceptions.
exception? Likewise,
The class Error and all its subclasses are
unchecked exceptions.

4 Most checked exceptions> VirtualMachineError, IOError, AssertionError,


frequently SQLException, ThreadDeath,
faced IOException, OutOfMemoryError, StackOverflowError.
exception and ClassNotFoundException
errors
unchecked exceptions>
NullPointerException,
ArithmeticException,

5 Why to catch Application must catch the Exception Application must not catch the Error
or not to because they does not cause any major because they does cause any major threat
catch? threat to application. to application.
Example >
Lets say errors like OutOfMemoryError and
StackOverflowError occur and are caught
then JVM might not be able to free up
memory for rest of application to execute, so
it will be better if application dont catch
these errors and is allowed to terminate.

1/2
2/2
Differences between throw and throws in java
www.javamadesoeasy.com /2015/05/differences-between-throw-and-throws-in.html

You are here : Home / Core Java Tutorials / Exceptions Tutorial in java

In this post we will be discussing differences between throw and throws

Differences between throw and throws in java >

throw throws

1 throw keyword is used to throw an exception throws keyword is used to declare an exception.
explicitly.

2 throw is used inside method. throws is used in method declaration.

Example > Example >


static void m(){ static void m() throws FileNotFoundException{
throw new FileNotFoundException(); }
}

3 throw is always followed by instanceof Exception throws is always followed by name of Exception class.
class.
Example >
Example > throws FileNotFoundException
throw new FileNotFoundException()

4 throw can be used to throw only one exception at throws can be used to throw multiple exception at time.
time.
Example >
Example > throws FileNotFoundException, NullPointerException
throw new FileNotFoundException()
and many more...

5 throw cannot propagate exception to calling throws can propagate exception to calling method.
method.
Please see these programs to understand how exception
is propagated to calling method.
Program 1 - Handling Exception by throwing it from m()
method (using throws keyword) and handling it in try-
catch block from where call to method m() was made.

Program 2 - Throwing Exception from m() method and


then again throwing it from calling method [ i.e. main
method]

Similarities between throw and throws in java >


1/2
Though there are not much similarities between two, but both are keywords in java.

2/2
Differences between Final, Finally and Finalize in java
www.javamadesoeasy.com /2015/05/final-finally-and-finalize-difference.html

You are here : Home / Core Java Tutorials / Exceptions Tutorial in java

final, finally and finalize all are used very frequently in java. This forms the core of java and one of the very
prominently asked interview question in java.

Difference between Final, Finally and Finalize

final finally finalize

1 final can be applied to variable, finally is a block. finalize is a method.


method and class in java.

2 try or try-catch block can be finalize method is called before garbage


2.1) Final variable followed by finally block > collection by JVM,
final memberVariable try-finally block, or finalize method is called for any
final local variable cleanup action that may be required
final static variable try{ before garbage collection.
//Code to be
Final memberVariable of class must enclosed in try-finally /** Copyright (c), AnkitMittal
be initialized at time of declaration, block JavaMadeSoEasy.com */
once initialized final memberVariable }finally{
cannot be assigned a new value. } @Override
Final variables are called constants protected void finalize()
in java. throws Throwable {
try-catch-finally block. try {
class FinalTest {
final int x=1; System.out.println("in
//memberVariable/instanceVariable try{ finalize() method, "
} //Code to be enclosed +
in try-catch-finally "doing cleanup activity");
block
}catch(Exception e){ } catch (Throwable
If constructor is defined then final }finally{
memberVariable can be initialized in throwable) {
} throw throwable;
constructor but once initialized
cannot be assigned a new value. }
}
finally block can can only
class FinalTest { exist if try or try-catch block
final int x; finalize() method is defined in
is there, finally block cant java.lang.Object
//memberVariable/instanceVariable be used alone in java.
FinalTest() {
x = 1; //final memberVariable finally block is not executed
can be initialized in constructor. in following scenarios >
} finally is not executed when
} System.exit is called.
if in case JVM crashes
Final local variable can be left because of some

1/3
uninitialized at time of declaration java.util.Error.
and can be initialized later, but once
initialized cannot be assigned a new
value.

class FinalTest {
void method(){
final int x; //uninitialized at time
of declaration
x=1;
}
}

Final static variable of class must be


initialized at time of declaration or
can be initialized in static block, once
initialized final static variable cannot
be assigned a new value.

If static block is defined then final


static variable can be initialized in
static block, once initialized final
static variable cannot be assigned a
new value.

class FinalTest {
final static int x; //static variable
static{ //static block
x=1;
}
}

2.2) Final method


Final method cannot be overridden,
any attempt to do so will cause
compilation error.

Runtime polymorphism is not


applicable on final methods because
they cannot be inherited.

2.3) Final class


Final class cannot be extended, any
attempt to do so will cause
compilation error.

2/3
3 - finally block can only exist if We can force early garbage collection
try or try-catch block is in java by using following methods >
there, finally block cant be System.gc();
used alone in java. Runtime.getRuntime().gc();
System.runFinalization();
Runtime.getRuntime().runFinalization();

4 - finally is always executed If any uncaught exception is thrown


irrespective of exception inside finalize method -
thrown. exception is ignored,
thread is terminated and
object is discarded.

Note : Any exception thrown by the


finalize method causes the finalization
of this object to be halted, but is
otherwise ignored.

5 - Currently executing thread JVM does not guarantee which


calls finally method. daemon thread will invoke the finalize
method for an object.

6 final is a keyword in java. finally Is a keyword in java. finalize is not a keyword in java.

3/3
Difference between multiple catch block and multi catch
syntax in java
www.javamadesoeasy.com /2015/05/difference-between-multiple-catch-block.html

You are here : Home / Core Java Tutorials / Exceptions Tutorial in java

In this post we will be discussing differences between multiple catch block and multi catch syntax

Difference between multiple catch block and multi catch syntax in java >

multiple catch block multi catch syntax

1 multiple catch blocks were introduced in prior multi catch syntax was introduced in java 7 for
versions of Java 7 and does not provide any improvements in multiple exception handling which helps
automatic resource management. in automatic resource management.

2 Here is the syntax for writing multiple catch block Here is the multi catch syntax >
>

try{ try{
//code . . . . . //code . . . . .
}catch(IOException ex1){ }catch(IOException | SQLException ex){
//code . . . . . //code . . . . .
} catch(SQLException ex2){ }
//code . . . . .
}
We could separate different exceptions using pipe ( | )

1/3
3 For catching IOException and SQLException we with the help of multi catch syntax we can catch
need to write two catch block like this > IOException and SQLException in one catch block using
multi catch syntax like this >

2/3
4 When multiple catch blocks are used , first catch If Multi catch syntax is used to catch subclass and its
block could be subclass of Exception class superclass than compilation error will be thrown.
handled in following catch blocks like this > IOException and Exception in multi catch syntax will
IOException is subclass of Exception. cause compilation error The exception IOException is
already caught by the alternative Exception.

Solution >
We must use only Exception to catch its subclass like this
>

5 Does not provide such features. Features of multi catch syntax >

Has improved way of catching multiple exceptions.


This syntax does not looks clumsy.
Reduces developer efforts of writing multiple catch
blocks.
Allows us to catch more than one exception in one
catch block.
Helps in automatic resource management.

3/3
Most common and frequently occurring checked,
unchecked Exceptions and Errors in java
www.javamadesoeasy.com /2016/07/most-common-and-frequently-occurring.html

You are here : Home / Core Java Tutorials / Exceptions Tutorial in java

In this tutorial we will learn Most common, important and frequently occurring checked and unchecked Exceptions in
java.

Contents of page >

1) Most common and frequently occurring checked (compile time) in java >
2) Most common and frequently occurring unchecked (runtime) in java.
3) Most common and frequently occurring Errors in java >
4) Few More Exception and Errors is java>

1) Most common and frequently occurring checked (compile time) in java >

IOException in java

FileNotFoundException in java

EOFException occurs and how to avoid it in java

SQLException in java

What is java.lang.InterruptedException in java

when java.lang.ClassNotFoundException occurs in java

Solve InvalidClassException in java

2) Most common and frequently occurring unchecked (runtime) in java.

What is java.lang.NullPointerException in java, when it occurs,how to handle, avoid and


fix it

NumberFormatException in java

IndexOutOfBoundsException in java

When java.lang.ArrayIndexOutOfBoundsException occurs in java

When java.lang.StringIndexOutOfBoundsException occurs in java


1/2
java.lang.ArithmeticException in java - Divide number by zero

When dividing by zero does not throw ArithmeticException in java

When java.lang.IllegalStateException occurs in java

when java.lang.IllegalMonitorStateException is thrown in java

Solve java.lang.UnsupportedOperationException in java

3) Most common and frequently occurring Errors in java >

OutOfMemoryError in java

When java.lang.StackOverflowError occurs in java

Solve java.lang.ExceptionInInitializerError in java

How to solve java.lang.NoClassDefFoundError in java

4) Few More Exception and Errors is java>

What is difference between ClassNotFoundException and NoClassDefFoundError in


java

Summary -
So in this tutorial we learned Most common, important and frequently occurring checked (compile time) and
unchecked (runtime) Exceptions and Errors in java.

Having any doubt? or you you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.

Labels: Core Java Exceptions

2/2
What is difference between ClassNotFoundException and
NoClassDefFoundError in java
www.javamadesoeasy.com /2015/12/what-is-difference-between.html

You are here : Home / Core Java Tutorials / Exceptions Tutorial in java

Difference between ClassNotFoundException and NoClassDefFoundError in java

ClassNotFoundException NoClassDefFoundError

1 ClassNotFoundException is Checked (compile NoClassDefFoundError is a Error in java.


time) Exception in java. Error and its subclasses are regarded as
unchecked exceptions in java.

2 Here is the hierarchy of Here is the hierarchy of


java.lang.ClassNotFoundException - java.lang.NoClassDefFoundError -

-java.lang.Object -java.lang.Object
-java.lang.Throwable -java.lang.Throwable
-java.lang.Exception -java.lang.Error
-java.lang.ReflectiveOperationException -java.lang.LinkageError
-java.lang.ClassNotFoundException -java.lang.NoClassDefFoundError

3 ClassNotFoundException is thrown when JVM tries NoClassDefFoundError is thrown when JVM tries to
to class from classpath but it does not find that load class which >
class.
was NOT available at runtime but
was available at compile time.

4 ClassNotFoundException is thrown whenever an These methods will never throw


java application tries to load a class by passing NoClassDefFoundError.
class name as String in following methods -

1. forName(String className) method of


java.lang.Class class.
2. findSystemClass(String name) method of
java.lang.ClassLoader class.
3. loadClass(String name) method of
java.lang.ClassLoader class.

ExceptionInInitializerError has got nothing to do You must ensure that class does not throws
with ClassNotFoundException. java.lang.ExceptionInInitializerError because that is
likely to be followed by NoClassDefFoundError.

1/8
Similarity between ClassNotFoundException and NoClassDefFoundError in java

ClassNotFoundException NoClassDefFoundError

ClassNotFoundException is thrown when JVM tries to class NoClassDefFoundError is thrown when JVM tries to load
from classpath but it unable to find that class. class but no definition of class could be found.
Or, you can simply say class was unavailable in classpath at
runtime. Or, you can simply say class was unavailable in classpath
at runtime.

Example/Programs/Scenarios where ClassNotFoundException may be thrown in java>

1. Loading classes via Reflection in java > ClassNotFoundException is thrown whenever an application tries to load a
class by passing class name as String in forName(String className) method of Class class.

Example -

package ClassNotFoundExceptionExamplePkg;
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class ClassNotFoundExceptionExample {
public static void main(String... a) {
System.out.println("initialize 'ReflectionClass' at runtime" );
// initialize 'ReflectionClass' at runtime
Class cls = null;
try {
cls = Class.forName("ClassNotFoundExceptionExamplePkg.ReflectionClass");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
/*OUTPUT
initialize 'ReflectionClass' at runtime
java.lang.ClassNotFoundException: ReflectionClass
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at
ClassNotFoundExceptionExamplePkg.ClassNotFoundExceptionExample.main(ClassNotFoundExceptionExample.java:12)
*/

Solution - Make class available in package ClassNotFoundExceptionExamplePkg and call


forName(String className) method of java.lang.Class class.

Example -

2/8
package ClassNotFoundExceptionExamplePkg;
class ReflectionClass {
static{
System.out.println("ReflectionClass has been initialized");
}
}
/**
* Copyright (c), AnkitMittal JavaMadeSoEasy.com
* Main class
*/
public class ClassNotFoundExceptionAvoidExample {
public static void main(String... a) {
System.out.println("initialize 'ReflectionClass' at runtime" );
// initialize 'ReflectionClass' at runtime
Class cls = null;
try {
cls = Class.forName("ClassNotFoundExceptionExamplePkg.ReflectionClass");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
/*OUTPUT
initialize 'ReflectionClass' at runtime
ReflectionClass has been initialized
*/

2. ClassNotFoundException can be thrown when java application tries to load/initialize oracle.jdbc.driver.OracleDriver


class by passing class name as String in Class.forName("oracle.jdbc.driver.OracleDriver") method of Class class but
OracleDriver class is not present in classpath.

Example -

package ClassNotFoundExceptionExamplePkg2;
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class MyJdbcConnectionSetup {
public static void main(String... arg) {
System.out.println("register Oracle driver class, i.e. initialize OracleDriver");
try {
// register Oracle driver class, i.e. initialize OracleDriver
Class.forName("oracle.jdbc.driver.OracleDriver");
System.out.println("Oracle driver class registered, i.e. initialized OracleDriver ");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
/*OUTPUT
register Oracle driver class, i.e. initialize OracleDriver
java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at
ClassNotFoundExceptionExamplePkg2.MyJdbcConnectionSetup.main(MyJdbcConnectionSetup.java:8)
*/

3/8
Solution - Make OracleDriver class available in classpath. Read how to configure java build path -
registering driver

Example -

package ClassNotFoundExceptionExamplePkg2;
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class MyJdbcConnectionSetup {
public static void main(String... arg) {
System.out.println("register Oracle driver class, i.e. initialize OracleDriver");
try {
// register Oracle driver class, i.e. initialize OracleDriver
Class.forName("oracle.jdbc.driver.OracleDriver");
System.out.println("Oracle driver class registered, i.e. initialized OracleDriver ");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
/*OUTPUT
register Oracle driver class, i.e. initialize OracleDriver
Oracle driver class registered, i.e. initialized OracleDriver
*/

Example/Programs/Scenarios where NoClassDefFoundError may be thrown in java>

1. We will create very simple program which will throw NoClassDefFoundError .

NoClassDefFoundError is thrown when JVM tries to load class but no definition of class could be found.

First lets write java class >

public class NoClassDefFoundErrorExample {


public static void main(String[] args) {
new A(); // It can throw java.lang.NoClassDefFoundError
}
}
class A {
}

Lets say above code in file = E:\workspace\NoClassDefFoundErrorExample.java

Go to CMD and type below commands >

4/8
C:\Users\ankitmittal01>e:

E:\>cd E:\workspace

E:\workspace>javac NoClassDefFoundErrorExample.java

E:\workspace>

As soon as javac NoClassDefFoundErrorExample.java is called two .class files are formed.

Directory of .class files = E:\workspace\NoClassDefFoundErrorExample.class and


E:\workspace\A.class

Now, when above program can throw NoClassDefFoundError?

Now, delete E:\workspace\A.class

Lets say you have deleted A.class. Now, let's execute the program again >

E:\workspace>java NoClassDefFoundErrorExample
Exception in thread "main" java.lang.NoClassDefFoundError: : A
at NoClassDefFoundErrorExample.main(NoClassDefFoundErrorExample.java:3)
Caused by: java.lang.ClassNotFoundException: A
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 1 more

E:\workspace>

As we see NoClassDefFoundError was thrown when JVM tries to load A.class which >

was NOT available at runtime but


was available at compile time.

2. If any RuntimeException occurs in >

static initialization block of class or


during initialing of the static variables

then NoClassDefFoundError may be thrown.

We will create another simple program to understand how RuntimeException occured in static block of class can throw
NoClassDefFoundError.

First lets write java class >

5/8
package noClassDefFoundErrorPkg;

public class NoClassDefFoundErrorExample {


public static void main(String[] args) {
try {
new A(); // It will throw java.lang.ExceptionInInitializerError
} catch (Error error) {
error.printStackTrace();
}

System.out.println("\n--------------\n" );

try {
new A(); // It will throw java.lang.NoClassDefFoundError
} catch (Error error) {
error.printStackTrace();
}
}
}
class A {
static {
System.out.println("In static block of class A" );
System.out.println(1 / 0); // It will throw java.lang.ArithmeticException
}
/*
* Constructor of class A will never get executed
*/
A() {
System.out.println("In constructor of class A" );
}
}

Output of above program >

In static block of class A


java.lang.ExceptionInInitializerError
at
noClassDefFoundErrorPkg.NoClassDefFoundErrorExample.main(NoClassDefFoundErrorExample.java:6)
Caused by: java.lang.ArithmeticException: / by zero
at noClassDefFoundErrorPkg.A.<clinit>(NoClassDefFoundErrorExample.java:27)
... 1 more
--------------
java.lang.NoClassDefFoundError: Could not initialize class noClassDefFoundErrorPkg.A
at
noClassDefFoundErrorPkg.NoClassDefFoundErrorExample.main(NoClassDefFoundErrorExample.java:14)

In the above program, first new A() at line 6 throwed ExceptionInInitializerError because ArithmeticException occurred in
initializing the class (i.e. in static block of class) then,
new A() at line 14 throwed NoClassDefFoundError because class initialization has already thrown error.

You must read ArithmeticException is an unchecked exception and it is propagated automatically in java.

3. We will create another program which uses commons-lang.jar and will throw NoClassDefFoundError .

NoClassDefFoundError is thrown when JVM tries to load class but no definition of class could be found.
6/8
First lets write java class >

import org.apache.commons.lang.StringUtils;
public class NoClassDefFoundErrorExample {
public static void main(String... arg) {
System.out.println(StringUtils.class + " loaded");
System.out.println(StringUtils.isNotEmpty("java")); //true
}
}

Lets say above code in file = E:\workspace\NoClassDefFoundErrorExample.java

Go to CMD and type below commands >

Set required jar (commons-lang.jar) in classpath


and then execute javac command.

C:\Users\ankitmittal01>e:

E:\>cd E:\workspace

E:\workspace>set CLASSPATH=.;E:\java jars\commons\commons-lang.jar

E:\workspace>javac NoClassDefFoundErrorExample.java

E:\workspace>

As soon as javac NoClassDefFoundErrorExample.java is called .class file is formed.

Directory of .class file = E:\workspace\NoClassDefFoundErrorExample.class

Now, when above program can throw NoClassDefFoundError?

Now, either unset the the classpath by using command >


set CLASSPATH=
Or,
Delete or move E:\java jars\commons\commons-lang.jar

Lets say you have unset the classpath. Now, let's execute the program again >

E:\workspace>set CLASSPATH=

E:\workspace>java NoClassDefFoundErrorExample
Exception in thread "main" java.lang.NoClassDefFoundError:
org/apache/commons/lang/StringUtils
at NoClassDefFoundErrorExample.main(NoClassDefFoundErrorExample.java:5)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.lang.StringUtils
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 1 more

E:\workspace>

7/8
As we see NoClassDefFoundError was thrown when JVM tries to load org.apache.commons.lang.StringUtils class which >

was NOT available at runtime but


was available at compile time.

Note : Jar used in above program = commons-lang.jar

8/8
EXCEPTIONS - Top 60 interview questions and answers in
java for fresher and experienced - detailed explanation with
diagrams Set-1 > Q1- Q25
www.javamadesoeasy.com /2015/05/exceptions-top-60-interview-questions_16.html

You are here : Home / Core Java Tutorials / Java Interview Questions and answers

Time to impress interviewer, crack EXCEPTION interview questions in java. Best set of questions, your interview will
comprise of mostly these questions. I have tried to cover almost all the possible questions which could be framed in
an interview by interviewer.

EXCEPTIONS - Top 60 interview questions and answers in java for fresher and experienced - 30 important OUTPUT
questions Set-2 > Q26- Q60

Exception interview Question 1. What is exception in java?


Answer. Its the basic Exception framework interview question. Freshers must know about this. Java Exception
handling provides a mechanism to handle compile and runtime errors in java.

To make application robust Exception must be handled appropriately,


by handling exceptions we end up giving some meaningful message to end user rather than giving
meaningless message in java.

Exception interview Question 2. Explain exception hierarchy in java?


Answer. Its also the basic Exception handling interview question. Freshers must know about this.
Exception hierarchy in java >

java.lang.Object is superclass of all classes in java.

java.lang.Throwable is superclass of java.lang.Exception and java.lang.Error

java.lang.Exception is superclass of java.lang.RuntimeException, IOException, SQLException,


BrokenBarrierException and many more other classes in java.
1/23
java.lang.RuntimeException is superclass of java.lang.NullPointerException, ArithmeticException and many more
other classes in java.

java.lang.Error is superclass of java.lang.VirtualMachineError, IOError, AssertionError, ThreadDeath and many more


other classes in java.

java.lang.VirtualMachineError is superclass of java.lang.OutOfMemoryError, StackOverflowError and many more


other classes in java.

Exception interview Question 3. What are differences between checked and unchecked exceptions in java?
Answer. This is very important Exception handling interview question in java.

Property checked exception unchecked exception

1 Also known as checked exceptions are also known as unchecked exceptions are also known as runtime
compileTime exceptions in java. exceptions in java.

2 Should be Checked exceptions are those which Unchecked exceptions are those which need to
solved at need to be taken care at compile time in be taken care at runtime in java.
compile or java.
runtime?

3 Benefit/ We cannot proceed until we fix Whenever runtime exception occurs execution of
Advantage compilation issues which are most likely program is interrupted, but by handling these kind
to happen in program, this helps us in of exception we avoid such interruptions and end
avoiding runtime problems upto lot of up giving some meaningful message to user in
extent in java. java.

4 Creating
custom/own
exception class UserException extends class UserException extends
Exception { RuntimeException {
UserException(String s) { UserException(String s) {
super(s); super(s);
} }
} }

By extending java.lang.Exception, we By extending java.lang.RuntimeException, we can


can create checked exception. create unchecked exception.

5 Exception For propagating checked exceptions unchecked exceptions are automatically


propagation method must throw exception by using propagated in java.
throws keyword.

2/23
6 handling If superclass method throws/declare If superclass method throws/declare unchecked >
checked and checked exception >
unchecked overridden method of subclass can
exception overridden method of subclass declare/throw any unchecked
while can declare/throw narrower /RuntimeException (superclass or
overriding (subclass of) checked exception subclass) (As shown in Program), or
superclass (As shown in Program), or overridden method of subclass cannot
method overridden method of subclass declare/throw any checked exception (As
cannot declare/throw broader shown in Program),
(superclass of) checked
exception (As shown in
Program), or
overridden method of subclass
can declare/throw any unchecked
/RuntimeException (As shown in
Program)

Which classes The class Exception and all its The class RuntimeException and all its
are which type subclasses that are not also subclasses subclasses are unchecked exceptions.
of exception? of RuntimeException are checked Likewise,
either exceptions in java. The class Error and all its subclasses are
checked or unchecked exceptions in java.
unchecked
exception?

7 Most SQLException, NullPointerException,


frequently IOException, ArithmeticException
faced ClassNotFoundException ArrayIndexOutOfBoundsException.
exceptions

Read more on : Checked (compile time exceptions) and UnChecked (RuntimeExceptions) in java - Definition and
differences

Exception interview Question 4. What are 5 exception handling keywords in java?


Answer. This is another very important exception handling interview question in java.
5 keyword in java exception handling in java

try - Any exception occurring in try block is catched by catch block.

catch - catch block is always followed by try block in java.

finally finally block can can only exist if try or try-catch block is there, finally block cant be used alone
in java.

Features of finally >

finally block is always executed irrespective of exception is thrown or not.

finally is keyword in java.

3/23
finally block is optional in java, we may use it or not.

finally block is not executed in following scenarios >

finally is not executed when System.exit is called.


if in case JVM crashes because of some java.util.Error.

throw throw is a keyword in java.

throw keyword allows us to throw checked or unchecked exception.

throws throws is written in methods definition to indicate that method can throw exception in java.

Exception interview Question 5. Explain what is Error in java?


Answer. Experienced developers must know in detail about Exception handling interview question in java.
java.lang.Error

Error is a subclass of Throwable in java.


Error indicates some serious problems that our application should not try to catch in java.
Errors are abnormal conditions in application.
Error and its subclasses are regarded as unchecked exceptions in java

Must know :
ThreadDeath is an error which application must not try to catch but it is normal condition in java.

Exception interview Question 6. What are differences between Exception and Error in java?
Answer. It is another very important exception interview question to differentiate between Exception and Error in
java.

Property Exception Error

1 serious Exception does not indicate any serious Error indicates some serious problems that
problem? problem. our application should not try to catch.

2 divided into Exception are divided into checked and Error are not divided further into such
checked and unchecked exceptions in java. classifications in java.
unchecked

3 Which classes The class Exception and all its subclasses Error and its subclasses are regarded as
are which type that are not also subclasses of unchecked exceptions in java
of exception? RuntimeException are checked exceptions.
either
checked or The class RuntimeException and all its
unchecked subclasses are unchecked exceptions.
exception? Likewise,
The class Error and all its subclasses are
unchecked exceptions in java.

4/23
4 Most frequently checked exceptions> VirtualMachineError, IOError, AssertionError,
faced exception SQLException, ThreadDeath,
and errors IOException, OutOfMemoryError, StackOverflowError.
ClassNotFoundException

unchecked exceptions>
NullPointerException, ArithmeticException,

5 Why to catch or Application must catch the Exception Application must not catch the Error because
not to catch? because they does not cause any major they does cause any major threat to
threat to application in java. application.
Example >
Lets say errors like OutOfMemoryError and
StackOverflowError occur and are caught
then JVM might not be able to free up
memory for rest of application to execute, so
it will be better if application dont catch
these errors and is allowed to terminate in
java.

Exception interview Question 7. Explain throw keyword in java?


Answer. This is also frequently asked exception handling interview question.

throw is a keyword in java.


throw keyword allows us to throw checked or unchecked exception.

throw unchecked exception in java >

We need not to handle unChecked exception either by catching it or throwing it in java.

We throw NullPointerException (unChecked exception) and didnt handled it, no compilation error was thrown in
5/23
java.

throw checked exception >

We need to handle checked exception either by catching it, or


throwing it by using throws keyword. (When thrown, exception must be handled in calling environment)

Exception interview Question 8. Explain throws keyword in java?


Answer. This exception interview question will be covered in below question but it give you more detailed
information about throw keyword in java.

throws is written in methods definition to indicate that method can throw exception.

throws unChecked exception in java >

We need not to handle unChecked exception either by catching it or throwing it.

Above code throws NullPointerException (unChecked exception) and didnt handled it from where method m() was
called and no compilation error was thrown.

throws Checked exception in java >

We need to handle checked exception either by catching it or throwing it further, if not handled we will face
compilation error.

Exception interview Question 9. What is difference between throw and throws in java?
Answer. This is also another important and frequently asked exception handling interview question. To confuse
6/23
interviewees Interviewers might give you code snippet and ask you to insert throw or throws keyword in java.

throw throws

1 throw keyword is used to throw an exception throws keyword is used to declare an exception in java.
explicitly in java.

2 throw is used inside method. throws is used in method declaration.

Example in java > Example in java >


static void m(){ static void m() throws FileNotFoundException{
throw new FileNotFoundException(); }
}

3 throw is always followed by instanceof Exception throws is always followed by name of Exception class in
class in java. java.

Example > Example >


throw new FileNotFoundException() throws FileNotFoundException

4 throw can be used to throw only one exception at throws can be used to throw multiple exception at time.
time.
Example >
Example > throws FileNotFoundException, NullPointerException
throw new FileNotFoundException()
and many more...

5 throw cannot propagate exception to calling method throws can propagate exception to calling method.
in java.
Please see these programs to understand how
exception is propagated to calling method.
Program 1 - Handling Exception by throwing it from m()
method (using throws keyword) and handling it in try-
catch block from where call to method m() was made.

Program 2 - Throwing Exception from m() method and


then again throwing it from calling method [ i.e. main
method]

Exception interview Question 10. How to create user defined checked and unchecked Exception in java?
Answer. Very important exception handling interview question. Interviewers generally expects interviewees to write
code to create checked and unchecked Exception in java.

Creating user defined checked exception in java >

class UserDefinedException extends Exception {


UserDefinedException(String s) {
super(s);
}
}

By extending java.lang.Exception, we can create checked exception.

Creating user defined unchecked exception in java >

7/23
class UserDefinedException extends RuntimeException {
UserDefinedException(String s) {
super(s);
}
}

By extending java.lang.RuntimeException, we can create unchecked exception.

Exception interview Question 11. How to use try-catch-finally in java? Can we use try,catch or finally block alone in
java?
Answer. This exception handling interview question will test your practical/basic understanding of Exception
handling in java.
We can enclose exception prone code in >

try-catch block, or
try-finally block, or
try-catch-finally block.

Using try-catch block in java

try{
//Code to be enclosed in try-catch block
}catch(Exception e){
}

Using try-finally block in java

try{
//Code to be enclosed in try-finally block
}finally{
}

We cannot use try block alone, it must be followed by either catch or finally.
Using only try block will cause compilation error

try{
//only try block will cause compilation error
}

Likewise, we cannot use catch block alone, it always follows try block.
Using only catch block will cause compilation error

catch{
//only catch block will cause compilation error
}

Likewise, we cannot use finally block alone, it always follows try block.
Using only finally block will cause compilation error
8/23
finally{
//only finally block will cause compilation error
}

Exception interview Question 12. Is it allowed to use multiple catch block in java?
Answer. Another exception handling interview question which will test your practical knowledge and understanding
of Exception handling in java. Java exception handling allows us to use multiple catch block in java.

Important Point about multiple catch block in java >

1. Exception class handled in starting catch block must be subclass of Exception class handled in following
catch blocks (otherwise we will face compilation error).
2. Either one of the multiple catch block will handle exception at time in java.

Program - Lets understand the concept of multiple catch block in java>

/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */


public class ExceptionTest {
public static void main(String[] args) {

try{
int i=10/0; //will throw ArithmeticException
}catch(ArithmeticException ae){
System.out.println("Exception handled - ArithmeticException" );
}catch(RuntimeException re){
System.out.println("Exception handled - RuntimeException");
}catch(Exception e){
System.out.println("Exception handled - Exception");
}
}
}
/*OUTPUT
Exception handled - ArithmeticException
*/

In the above above >


ArithmeticException has been used in first catch block
RuntimeException has been used in second catch block
Exception has been used in third catch block

Exception is superclass of RuntimeException and


RuntimeException is superclass of ArithmeticException.

Exception interview Question 13. What is Automatic resource management in java 7?


Answer. Experienced java developers must be well versed with this exception interview question. As we know java
allows us to handle multiple exceptions by using multiple catch blocks. Now, java 7 has done improvements in
multiple exception handling by introducing multi catch syntax which helps in automatic resource management.

Features of multi catch syntax in java >

9/23
Has improved way of catching multiple exceptions.
This syntax does not looks clumsy in java.
Reduces developer efforts of writing multiple catch blocks in java.
Allows us to catch more than one exception in one catch block.

Here is the multi catch syntax >

try{
//code . . . . .
}catch(IOException | SQLException ex){
//code . . . . .
}

We could separate different exceptions using pipe ( | ) in java.

Exception interview Question 14. Explain try-with-resource in java?


Answer. Again experienced java developers must be well versed with this exception interview question. Before java
7, we used to write explicit code for closing file in finally block by using try-finally block like this >

/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */


public class TryWithResourseTest {
public static void main(String[] args) throws IOException {
InputStream inputStream = null;
try{
inputStream = new FileInputStream("c:/txtFile.txt");
//code......
}finally{
if(inputStream!=null)
inputStream.close();
}
}
}

In java 7, using Try-with-resources >

we need not to write explicit code for closing file.

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class TryWithResourseTest {
public static void main(String[] args) throws IOException {
try (InputStream inputStream = new FileInputStream("c:/txtFile.txt")) {
//code...
}
}
}

Using multiple resources inside Try-with-resources is also allowed in java.

10/23
Exception interview Question 15. Now, question comes why we need not to close file when we are using Try-with-
resources in java?
Answer. Again experienced java developers must be well versed with this exception interview question. Because
FileInputStream implements java.lang.AutoCloseable interface (AutoCloseable interfaces close method
automatically closes resources which are no longer needed) in java.

Which classes can be used inside Try-with-resources in java?


All the classes which implements AutoCloseable interface can be used inside Try-with-resources in java.

Exception interview Question 16. Explain finally keyword in java?


Answer. Fresher and experienced java developers must be well versed with this exception handling interview
question in java.
try or try-catch block can be followed by finally block in java >

try-finally block, or

try{
//Code to be enclosed in try-finally block
}finally{
}

try-catch-finally block.

try{
//Code to be enclosed in try-catch-finally block
}catch(Exception e){
}finally{
}

finally block can can only exist if try or try-catch block is there, finally block cant be used alone in java.

Features of finally in java >

finally block is always executed irrespective of exception is thrown or not.


finally is keyword in java.

finally block is not executed in following scenarios in java >

finally is not executed when System.exit is called.


if in case JVM crashes because of some java.util.Error.

Application of finally block in java programs in java >

We may use finally block to execute code for database connection closing , because closing connection in try
or catch block may not be safe.

Why closing connection in try block may not be safe?

11/23
Because exception may be thrown in try block before reaching connection closing statement.

Why closing connection in catch block may not be safe?


Because inappropriate exception may be thrown in try block and we might not enter catch block to
close connection in java.

For programs to demonstrate finally. Please refer this post.

Exception interview Question 17. Is it allowed to use nested try-catch in java?


Answer. Its basic java exception handling interview question.
java exception handling allows us to use nested try-catch block.

Nested try-catch block means using try-catch block inside another try-catch block in java.

/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */


public class ExceptionTest {
public static void main(String[] args) {

try{
int i=10/0; //will throw ArithmeticException
}catch(ArithmeticException ae){
System.out.println("try-catch block handled - ArithmeticException" );

//using nested try-catch block


try{
String s=null;
s.charAt(0); //will throw NullPointerException
}catch(NullPointerException npe){
System.out.println("NESTED try-catch block handled - "
+ "NullPointerException");
}

}
}
}

Exception interview Question 18. Discuss which checked and unchecked exception can be thrown/declared by
subclass method while overriding superclass method in java?
Answer. Its very very important exception handling interview question. Experienced and freshers all must be able to
answer this question.

If superclass method throws/declare unchecked/RuntimeException in java >

overridden method of subclass can declare/throw any unchecked /RuntimeException (superclass or


subclass), or
overridden method of subclass cannot declare/throw any checked exception in java , or
overridden method of subclass can declare/throw same exception in java, or
overridden method of subclass may not declare/throw any exception in java.

12/23
If superclass method throws/declare checked/compileTime exception in java >

overridden method of subclass can declare/throw narrower (subclass of) checked exception, or
overridden method of subclass cannot declare/throw broader (superclass of) checked exception, or
overridden method of subclass can declare/throw any unchecked /RuntimeException, or
overridden method of subclass can declare/throw same exception, or
overridden method of subclass may not declare/throw any exception in java.

If superclass method does not throw/declare any exception in java >

overridden method of subclass can declare/throw any unchecked /RuntimeException , or


overridden method of subclass cannot declare/throw any checked exception, or
overridden method of subclass may not declare/throw any exception in java.

For programs please refer > Throw/declare checked and unchecked exception while overriding superclass method
in java

Exception interview Question 19. What will happen when catch and finally block both return value, also when try and
finally both return value in java?
Answer. This is very important exception handling interview question for experienced developers.

When catch and finally block both return value, method will ultimately return value returned by finally block
irrespective of value returned by catch block.

/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */


public class ExceptionTest {
public static void main(String[] args) {
System.out.println("method return -> " +m());
}

static String m(){


try{
int i=10/0; //will throw ArithmeticException
}catch(ArithmeticException e){
return "catch";
}finally{
return "finally";
}

}
}
/*OUTPUT
method return -> finally
*/

In above program, i=10/0 will throw ArithmeticException and enter catch block to return "catch", but ultimately
control will enter finally block to return "finally".

Likewise, when try and finally block both return value, method will ultimately return value returned by finally block

13/23
irrespective of value returned by try block. For program please refer.

Exception interview Question 20. What is exception propagation in java?


Answer.
Experienced developers must know in detail about Exception handling interview question in java. Even freshers
must try and understand this in depth concept of exception propagation in java.
Whenever methods are called stack is formed and an exception is first thrown from the top of the stack and if it is not
caught, it starts coming down the stack to previous methods until it is not caught.
If exception remains uncaught even after reaching bottom of the stack it is propagated to JVM and program is
terminated in java.

Propagating unchecked exception (NullPointerException) >


unchecked exceptions are automatically propagated in java.

stack of methods is formed >

14/23
In the above program, stack is formed and an exception is first thrown
from the top of the stack [ method3() ] and it remains uncaught there,
and starts coming down the stack to previous methods to method2(),
then to method1(), than to main() and it remains uncaught throughout.
exception remains uncaught even after reaching bottom of the stack [
main() ] so it is propagated to JVM and ultimately program is terminated
by throwing exception [ as shown in output ] in java.

Propagating checked exception (FileNotFoundException) using throws


keyword >
For propagating checked exceptions method must throw exception by
using throws keyword.

Exception interview Question 21. Can a catch or finally block throw exception in java?
Answer. Yes, catch or finally block can throw checked or unchecked exception but it must be handled accordingly.
Please refer this post for handling checked and unchecked exceptions in java.

Exception interview Question 22. Why shouldnt you use Exception for catching all exceptions in java?
Answer. Catching Exception rather than handling specific exception can be vulnerable to our application. Multiple
catch blocks must be used to catch specific exceptions, because handling specific exception gives developer the

15/23
liberty of taking appropriate action and develop robust application.

Exception interview Question 23. What is Difference between multiple catch block and multi catch syntax?
Answer. Experienced developers must know in detail about this Exception handling interview question in java

multiple catch block multi catch syntax

1 multiple catch blocks were introduced in prior multi catch syntax was introduced in java 7 for
versions of Java 7 and does not provide any improvements in multiple exception handling which
automatic resource management in java. helps in automatic resource management in java.

2 Here is the syntax for writing multiple catch Here is the multi catch syntax in java >
block in java >

try{ try{
//code . . . . . //code . . . . .
}catch(IOException ex1){ }catch(IOException | SQLException ex){
//code . . . . . //code . . . . .
} catch(SQLException ex2){ }
//code . . . . .
}
We could separate different exceptions using pipe ( | )

3 For catching IOException and SQLException with the help of multi catch syntax we can catch
we need to write two catch block like this > IOException and SQLException in one catch block using
multi catch syntax like this >

16/23
4 When multiple catch blocks are used , first If Multi catch syntax is used to catch subclass and its
catch block could be subclass of Exception superclass than compilation error will be thrown.
class handled in following catch blocks like this IOException and Exception in multi catch syntax will
> cause compilation error The exception IOException is
IOException is subclass of Exception in java. already caught by the alternative Exception.

Solution >
We must use only Exception to catch its subclass like
this >

5 Does not provide such features. Features of multi catch syntax >

Has improved way of catching multiple


exceptions.
This syntax does not looks clumsy.
Reduces developer efforts of writing multiple
catch blocks.
Allows us to catch more than one exception in
one catch block.
Helps in automatic resource management.

For more read : Difference between multiple catch block and multi catch syntax

Exception interview Question 24. can a method be overloaded on basis of exceptions in java ?
Answer.
Another Exception handling interview question which will test your practical understanding of exception in java.

17/23
Yes a method be overloaded on basis of exceptions in java.

But now question which overloaded exception will be called.


Lets take an example :
Ques. Let's say one method handles Exception and other handles ArithmeticException. Which method will be
invoked when ArithmeticException is thrown?
Ans. Method which handles more specific exception will be called.

Program >

import java.io.IOException;
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com
* Main class */
public class ExceptionTest {

void method(Exception e){


System.out.println(e+" caught in Exception method");
}
void method(ArithmeticException ae){
System.out.println(ae+" caught in ArithmeticException method" );
}

public static void main(String[] args) {


ExceptionTest obj=new ExceptionTest();
obj.method(new ArithmeticException());
obj.method(new IOException());
}
}
/* OUTPUT
java.lang.ArithmeticException caught in ArithmeticException method
java.io.IOException caught in Exception method
*/

Exception interview Question 25. Mention few exception handling best practices in java?
Answer. Experienced developers must be able to answer this Exception handling interview question in detail in java.

Throw exceptions when the method cannot handle the exception, and more importantly, must be handled by
the caller.

Example -
In Servlets - doGet() and doPost() throw ServletException or IOException in certain circumstances where the
request could not be read correctly. Neither of these methods are in a position to handle the exception, but the
container is (which generally results in the 404 error page in most cases).

Bubble the exception if the method cannot handle it. This is a corollary of the above point, but applicable to
methods that must catch the exception. If the caught exception cannot be handled correctly by the method,
then it is preferable to bubble it.

Throw the exception right away. If an exception scenario is encountered, then it is a good practice to throw
an exception indicating the original point of failure, instead of attempting to handle the failure via error codes,
until a point deemed suitable for throwing the exception. In other words, attempt to minimize mixing exception
handling with error handling.
18/23
Either log the exception or bubble it, but don't do both. Logging an exception often indicates that the
exception stack has been completely unwound, indicating that no further bubbling of the exception has
occurred. Hence, it is not recommended to do both at the same time, as it often leads to a frustrating
experience in debugging.

Application should not try to catch Error - Because, in most of cases recovery from an Error is almost
impossible. So, application must be allowed to terminate.

Example>
Lets say errors like OutOfMemoryError and StackOverflowError occur and are caught then JVM might not be able
to free up memory for rest of application to execute, so it will be better if application dont catch these errors and is
allowed to terminate.

Read : Complete list of Exception handling best practices and guidelines for using exceptions in java

Exception interview Question 26. Difference between Final, Finally and Finalize in java?
Answer. It is another very very important exception interview question to differentiate between final, finally and
finalize in java.

final finally finalize

1 final can be applied to variable, finally is a block. finalize is a method.


method and class in java.

2 try or try-catch block can be finalize method is called before garbage


2.1) Final variable followed by finally block > collection by JVM,
final memberVariable try-finally block, or finalize method is called for any
final local variable cleanup action that may be required
final static variable try{ before garbage collection.
//Code to be
Final memberVariable of class must enclosed in try-finally /** Copyright (c), AnkitMittal
be initialized at time of declaration, block JavaMadeSoEasy.com */
once initialized final memberVariable }finally{
cannot be assigned a new value. } @Override
Final variables are called constants protected void finalize()
in java. throws Throwable {
try-catch-finally block. try {
class FinalTest {
final int x=1; System.out.println("in
//memberVariable/instanceVariable try{ finalize() method, "
} //Code to be enclosed +
in try-catch-finally "doing cleanup activity");
block
}catch(Exception e){ } catch (Throwable
If constructor is defined then final }finally{
memberVariable can be initialized in throwable) {
} throw throwable;
constructor but once initialized
cannot be assigned a new value. }
}
finally block can can only
exist if try or try-catch block finalize() method is defined in
is there, finally block cant java.lang.Object
be used alone in java.
19/23
class FinalTest { finally block is not executed
final int x; in following scenarios >
//memberVariable/instanceVariable finally is not executed when
FinalTest() { System.exit is called.
x = 1; //final memberVariable if in case JVM crashes
can be initialized in constructor. because of some
} java.util.Error.
}

Final local variable can be left


uninitialized at time of declaration
and can be initialized later, but once
initialized cannot be assigned a new
value in java.

class FinalTest {
void method(){
final int x; //uninitialized at time
of declaration
x=1;
}
}

Final static variable of class must be


initialized at time of declaration or
can be initialized in static block, once
initialized final static variable cannot
be assigned a new value.

If static block is defined then final


static variable can be initialized in
static block, once initialized final
static variable cannot be assigned a
new value.

class FinalTest {
final static int x; //static variable
static{ //static block
x=1;
}
}

2.2) Final method


Final method cannot be overridden,
any attempt to do so will cause
compilation error.

Runtime polymorphism is not


applicable on final methods because
they cannot be inherited.

2.3) Final class


Final class cannot be extended, any
20/23
attempt to do so will cause
compilation error.

3 - finally block can only exist if We can force early garbage collection
try or try-catch block is in java by using following methods >
there, finally block cant be System.gc();
used alone in java. Runtime.getRuntime().gc();
System.runFinalization();
Runtime.getRuntime().runFinalization();

4 - finally is always executed If any uncaught exception is thrown


irrespective of exception inside finalize method -
thrown in java. exception is ignored,
thread is terminated and
object is discarded.

Note : Any exception thrown by the


finalize method causes the finalization
of this object to be halted, but is
otherwise ignored.

5 - Currently executing thread JVM does not guarantee which


calls finally method in java. daemon thread will invoke the finalize
method for an object.

6 final is a keyword in java. finally Is a keyword in java. finalize is not a keyword in java.

For more detail read : Final, Finally and Finalize - difference and similarity in java

Another Exception interview Question. What are the differences between between ClassNotFoundException and
NoClassDefFoundError in java ?

Answer.

ClassNotFoundException NoClassDefFoundError

1 ClassNotFoundException is Checked NoClassDefFoundError is a Error in


(compile time) Exception in java. java. Error and its subclasses are
regarded as unchecked exceptions in
java.

21/23
2 Here is the hierarchy of Here is the hierarchy of
java.lang.ClassNotFoundException - java.lang.NoClassDefFoundError -

-java.lang.Object -java.lang.Object
-java.lang.Throwable -java.lang.Throwable
-java.lang.Exception -java.lang.Error
-java.lang.ReflectiveOperationException -java.lang.LinkageError
-java.lang.ClassNotFoundException -java.lang.NoClassDefFoundError

3 ClassNotFoundException is thrown when NoClassDefFoundError is thrown when JVM


JVM tries to class from classpath but it does tries to load class which >
not find that class.
was NOT available at runtime but
was available at compile time.

ExceptionInInitializerError has got nothing to You must ensure that class does not throws
do with ClassNotFoundException. java.lang.ExceptionInInitializerError because
that is likely to be followed by
NoClassDefFoundError.

For more read differences between between ClassNotFoundException and NoClassDefFoundError in java

Another very important Exception interview Question. What are the most important frequently occurring Exception
and Errors which you faced in java?
Answer. Most common and frequently occurring checked (compile time) and Errors in java >

FileNotFoundException in java

SQLException in java

What is java.lang.InterruptedException in java

when java.lang.ClassNotFoundException occurs in java

Most common and frequently occurring unchecked (runtime) in java.

What is java.lang.NullPointerException in java, when it occurs,how to handle, avoid and


fix it

NumberFormatException in java

IndexOutOfBoundsException in java

When java.lang.ArrayIndexOutOfBoundsException occurs in java

When java.lang.StringIndexOutOfBoundsException occurs in java

java.lang.ArithmeticException in java - Divide number by zero

22/23
When dividing by zero does not throw ArithmeticException in java

When java.lang.IllegalStateException occurs in java

when java.lang.IllegalMonitorStateException is thrown in java

Solve java.lang.UnsupportedOperationException in java

Most common and frequently occurring Errors in java >

OutOfMemoryError in java

When java.lang.StackOverflowError occurs in java

Solve java.lang.ExceptionInInitializerError in java

How to solve java.lang.NoClassDefFoundError in java

For Q26- Q60 please read > 30 important OUTPUT questions Set-2

(JMSE.

23/23
EXCEPTIONS - Top 60 interview questions and answers in
java for fresher and experienced - detailed explanation with
diagrams Set-1 > Q1- Q25
www.javamadesoeasy.com /2015/05/exceptions-top-60-interview-questions_16.html

You are here : Home / Core Java Tutorials / Java Interview Questions and answers

Time to impress interviewer, crack EXCEPTION interview questions in java. Best set of questions, your interview will
comprise of mostly these questions. I have tried to cover almost all the possible questions which could be framed in
an interview by interviewer.

EXCEPTIONS - Top 60 interview questions and answers in java for fresher and experienced - 30 important OUTPUT
questions Set-2 > Q26- Q60

Exception interview Question 1. What is exception in java?


Answer. Its the basic Exception framework interview question. Freshers must know about this. Java Exception
handling provides a mechanism to handle compile and runtime errors in java.

To make application robust Exception must be handled appropriately,


by handling exceptions we end up giving some meaningful message to end user rather than giving
meaningless message in java.

Exception interview Question 2. Explain exception hierarchy in java?


Answer. Its also the basic Exception handling interview question. Freshers must know about this.
Exception hierarchy in java >

java.lang.Object is superclass of all classes in java.

java.lang.Throwable is superclass of java.lang.Exception and java.lang.Error

java.lang.Exception is superclass of java.lang.RuntimeException, IOException, SQLException,


BrokenBarrierException and many more other classes in java.
1/23
java.lang.RuntimeException is superclass of java.lang.NullPointerException, ArithmeticException and many more
other classes in java.

java.lang.Error is superclass of java.lang.VirtualMachineError, IOError, AssertionError, ThreadDeath and many more


other classes in java.

java.lang.VirtualMachineError is superclass of java.lang.OutOfMemoryError, StackOverflowError and many more


other classes in java.

Exception interview Question 3. What are differences between checked and unchecked exceptions in java?
Answer. This is very important Exception handling interview question in java.

Property checked exception unchecked exception

1 Also known as checked exceptions are also known as unchecked exceptions are also known as runtime
compileTime exceptions in java. exceptions in java.

2 Should be Checked exceptions are those which Unchecked exceptions are those which need to
solved at need to be taken care at compile time in be taken care at runtime in java.
compile or java.
runtime?

3 Benefit/ We cannot proceed until we fix Whenever runtime exception occurs execution of
Advantage compilation issues which are most likely program is interrupted, but by handling these kind
to happen in program, this helps us in of exception we avoid such interruptions and end
avoiding runtime problems upto lot of up giving some meaningful message to user in
extent in java. java.

4 Creating
custom/own
exception class UserException extends class UserException extends
Exception { RuntimeException {
UserException(String s) { UserException(String s) {
super(s); super(s);
} }
} }

By extending java.lang.Exception, we By extending java.lang.RuntimeException, we can


can create checked exception. create unchecked exception.

5 Exception For propagating checked exceptions unchecked exceptions are automatically


propagation method must throw exception by using propagated in java.
throws keyword.

2/23
6 handling If superclass method throws/declare If superclass method throws/declare unchecked >
checked and checked exception >
unchecked overridden method of subclass can
exception overridden method of subclass declare/throw any unchecked
while can declare/throw narrower /RuntimeException (superclass or
overriding (subclass of) checked exception subclass) (As shown in Program), or
superclass (As shown in Program), or overridden method of subclass cannot
method overridden method of subclass declare/throw any checked exception (As
cannot declare/throw broader shown in Program),
(superclass of) checked
exception (As shown in
Program), or
overridden method of subclass
can declare/throw any unchecked
/RuntimeException (As shown in
Program)

Which classes The class Exception and all its The class RuntimeException and all its
are which type subclasses that are not also subclasses subclasses are unchecked exceptions.
of exception? of RuntimeException are checked Likewise,
either exceptions in java. The class Error and all its subclasses are
checked or unchecked exceptions in java.
unchecked
exception?

7 Most SQLException, NullPointerException,


frequently IOException, ArithmeticException
faced ClassNotFoundException ArrayIndexOutOfBoundsException.
exceptions

Read more on : Checked (compile time exceptions) and UnChecked (RuntimeExceptions) in java - Definition and
differences

Exception interview Question 4. What are 5 exception handling keywords in java?


Answer. This is another very important exception handling interview question in java.
5 keyword in java exception handling in java

try - Any exception occurring in try block is catched by catch block.

catch - catch block is always followed by try block in java.

finally finally block can can only exist if try or try-catch block is there, finally block cant be used alone
in java.

Features of finally >

finally block is always executed irrespective of exception is thrown or not.

finally is keyword in java.

3/23
finally block is optional in java, we may use it or not.

finally block is not executed in following scenarios >

finally is not executed when System.exit is called.


if in case JVM crashes because of some java.util.Error.

throw throw is a keyword in java.

throw keyword allows us to throw checked or unchecked exception.

throws throws is written in methods definition to indicate that method can throw exception in java.

Exception interview Question 5. Explain what is Error in java?


Answer. Experienced developers must know in detail about Exception handling interview question in java.
java.lang.Error

Error is a subclass of Throwable in java.


Error indicates some serious problems that our application should not try to catch in java.
Errors are abnormal conditions in application.
Error and its subclasses are regarded as unchecked exceptions in java

Must know :
ThreadDeath is an error which application must not try to catch but it is normal condition in java.

Exception interview Question 6. What are differences between Exception and Error in java?
Answer. It is another very important exception interview question to differentiate between Exception and Error in
java.

Property Exception Error

1 serious Exception does not indicate any serious Error indicates some serious problems that
problem? problem. our application should not try to catch.

2 divided into Exception are divided into checked and Error are not divided further into such
checked and unchecked exceptions in java. classifications in java.
unchecked

3 Which classes The class Exception and all its subclasses Error and its subclasses are regarded as
are which type that are not also subclasses of unchecked exceptions in java
of exception? RuntimeException are checked exceptions.
either
checked or The class RuntimeException and all its
unchecked subclasses are unchecked exceptions.
exception? Likewise,
The class Error and all its subclasses are
unchecked exceptions in java.

4/23
4 Most frequently checked exceptions> VirtualMachineError, IOError, AssertionError,
faced exception SQLException, ThreadDeath,
and errors IOException, OutOfMemoryError, StackOverflowError.
ClassNotFoundException

unchecked exceptions>
NullPointerException, ArithmeticException,

5 Why to catch or Application must catch the Exception Application must not catch the Error because
not to catch? because they does not cause any major they does cause any major threat to
threat to application in java. application.
Example >
Lets say errors like OutOfMemoryError and
StackOverflowError occur and are caught
then JVM might not be able to free up
memory for rest of application to execute, so
it will be better if application dont catch
these errors and is allowed to terminate in
java.

Exception interview Question 7. Explain throw keyword in java?


Answer. This is also frequently asked exception handling interview question.

throw is a keyword in java.


throw keyword allows us to throw checked or unchecked exception.

throw unchecked exception in java >

We need not to handle unChecked exception either by catching it or throwing it in java.

We throw NullPointerException (unChecked exception) and didnt handled it, no compilation error was thrown in
5/23
java.

throw checked exception >

We need to handle checked exception either by catching it, or


throwing it by using throws keyword. (When thrown, exception must be handled in calling environment)

Exception interview Question 8. Explain throws keyword in java?


Answer. This exception interview question will be covered in below question but it give you more detailed
information about throw keyword in java.

throws is written in methods definition to indicate that method can throw exception.

throws unChecked exception in java >

We need not to handle unChecked exception either by catching it or throwing it.

Above code throws NullPointerException (unChecked exception) and didnt handled it from where method m() was
called and no compilation error was thrown.

throws Checked exception in java >

We need to handle checked exception either by catching it or throwing it further, if not handled we will face
compilation error.

Exception interview Question 9. What is difference between throw and throws in java?
Answer. This is also another important and frequently asked exception handling interview question. To confuse
6/23
interviewees Interviewers might give you code snippet and ask you to insert throw or throws keyword in java.

throw throws

1 throw keyword is used to throw an exception throws keyword is used to declare an exception in java.
explicitly in java.

2 throw is used inside method. throws is used in method declaration.

Example in java > Example in java >


static void m(){ static void m() throws FileNotFoundException{
throw new FileNotFoundException(); }
}

3 throw is always followed by instanceof Exception throws is always followed by name of Exception class in
class in java. java.

Example > Example >


throw new FileNotFoundException() throws FileNotFoundException

4 throw can be used to throw only one exception at throws can be used to throw multiple exception at time.
time.
Example >
Example > throws FileNotFoundException, NullPointerException
throw new FileNotFoundException()
and many more...

5 throw cannot propagate exception to calling method throws can propagate exception to calling method.
in java.
Please see these programs to understand how
exception is propagated to calling method.
Program 1 - Handling Exception by throwing it from m()
method (using throws keyword) and handling it in try-
catch block from where call to method m() was made.

Program 2 - Throwing Exception from m() method and


then again throwing it from calling method [ i.e. main
method]

Exception interview Question 10. How to create user defined checked and unchecked Exception in java?
Answer. Very important exception handling interview question. Interviewers generally expects interviewees to write
code to create checked and unchecked Exception in java.

Creating user defined checked exception in java >

class UserDefinedException extends Exception {


UserDefinedException(String s) {
super(s);
}
}

By extending java.lang.Exception, we can create checked exception.

Creating user defined unchecked exception in java >

7/23
class UserDefinedException extends RuntimeException {
UserDefinedException(String s) {
super(s);
}
}

By extending java.lang.RuntimeException, we can create unchecked exception.

Exception interview Question 11. How to use try-catch-finally in java? Can we use try,catch or finally block alone in
java?
Answer. This exception handling interview question will test your practical/basic understanding of Exception
handling in java.
We can enclose exception prone code in >

try-catch block, or
try-finally block, or
try-catch-finally block.

Using try-catch block in java

try{
//Code to be enclosed in try-catch block
}catch(Exception e){
}

Using try-finally block in java

try{
//Code to be enclosed in try-finally block
}finally{
}

We cannot use try block alone, it must be followed by either catch or finally.
Using only try block will cause compilation error

try{
//only try block will cause compilation error
}

Likewise, we cannot use catch block alone, it always follows try block.
Using only catch block will cause compilation error

catch{
//only catch block will cause compilation error
}

Likewise, we cannot use finally block alone, it always follows try block.
Using only finally block will cause compilation error
8/23
finally{
//only finally block will cause compilation error
}

Exception interview Question 12. Is it allowed to use multiple catch block in java?
Answer. Another exception handling interview question which will test your practical knowledge and understanding
of Exception handling in java. Java exception handling allows us to use multiple catch block in java.

Important Point about multiple catch block in java >

1. Exception class handled in starting catch block must be subclass of Exception class handled in following
catch blocks (otherwise we will face compilation error).
2. Either one of the multiple catch block will handle exception at time in java.

Program - Lets understand the concept of multiple catch block in java>

/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */


public class ExceptionTest {
public static void main(String[] args) {

try{
int i=10/0; //will throw ArithmeticException
}catch(ArithmeticException ae){
System.out.println("Exception handled - ArithmeticException" );
}catch(RuntimeException re){
System.out.println("Exception handled - RuntimeException");
}catch(Exception e){
System.out.println("Exception handled - Exception");
}
}
}
/*OUTPUT
Exception handled - ArithmeticException
*/

In the above above >


ArithmeticException has been used in first catch block
RuntimeException has been used in second catch block
Exception has been used in third catch block

Exception is superclass of RuntimeException and


RuntimeException is superclass of ArithmeticException.

Exception interview Question 13. What is Automatic resource management in java 7?


Answer. Experienced java developers must be well versed with this exception interview question. As we know java
allows us to handle multiple exceptions by using multiple catch blocks. Now, java 7 has done improvements in
multiple exception handling by introducing multi catch syntax which helps in automatic resource management.

Features of multi catch syntax in java >

9/23
Has improved way of catching multiple exceptions.
This syntax does not looks clumsy in java.
Reduces developer efforts of writing multiple catch blocks in java.
Allows us to catch more than one exception in one catch block.

Here is the multi catch syntax >

try{
//code . . . . .
}catch(IOException | SQLException ex){
//code . . . . .
}

We could separate different exceptions using pipe ( | ) in java.

Exception interview Question 14. Explain try-with-resource in java?


Answer. Again experienced java developers must be well versed with this exception interview question. Before java
7, we used to write explicit code for closing file in finally block by using try-finally block like this >

/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */


public class TryWithResourseTest {
public static void main(String[] args) throws IOException {
InputStream inputStream = null;
try{
inputStream = new FileInputStream("c:/txtFile.txt");
//code......
}finally{
if(inputStream!=null)
inputStream.close();
}
}
}

In java 7, using Try-with-resources >

we need not to write explicit code for closing file.

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class TryWithResourseTest {
public static void main(String[] args) throws IOException {
try (InputStream inputStream = new FileInputStream("c:/txtFile.txt")) {
//code...
}
}
}

Using multiple resources inside Try-with-resources is also allowed in java.

10/23
Exception interview Question 15. Now, question comes why we need not to close file when we are using Try-with-
resources in java?
Answer. Again experienced java developers must be well versed with this exception interview question. Because
FileInputStream implements java.lang.AutoCloseable interface (AutoCloseable interfaces close method
automatically closes resources which are no longer needed) in java.

Which classes can be used inside Try-with-resources in java?


All the classes which implements AutoCloseable interface can be used inside Try-with-resources in java.

Exception interview Question 16. Explain finally keyword in java?


Answer. Fresher and experienced java developers must be well versed with this exception handling interview
question in java.
try or try-catch block can be followed by finally block in java >

try-finally block, or

try{
//Code to be enclosed in try-finally block
}finally{
}

try-catch-finally block.

try{
//Code to be enclosed in try-catch-finally block
}catch(Exception e){
}finally{
}

finally block can can only exist if try or try-catch block is there, finally block cant be used alone in java.

Features of finally in java >

finally block is always executed irrespective of exception is thrown or not.


finally is keyword in java.

finally block is not executed in following scenarios in java >

finally is not executed when System.exit is called.


if in case JVM crashes because of some java.util.Error.

Application of finally block in java programs in java >

We may use finally block to execute code for database connection closing , because closing connection in try
or catch block may not be safe.

Why closing connection in try block may not be safe?

11/23
Because exception may be thrown in try block before reaching connection closing statement.

Why closing connection in catch block may not be safe?


Because inappropriate exception may be thrown in try block and we might not enter catch block to
close connection in java.

For programs to demonstrate finally. Please refer this post.

Exception interview Question 17. Is it allowed to use nested try-catch in java?


Answer. Its basic java exception handling interview question.
java exception handling allows us to use nested try-catch block.

Nested try-catch block means using try-catch block inside another try-catch block in java.

/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */


public class ExceptionTest {
public static void main(String[] args) {

try{
int i=10/0; //will throw ArithmeticException
}catch(ArithmeticException ae){
System.out.println("try-catch block handled - ArithmeticException" );

//using nested try-catch block


try{
String s=null;
s.charAt(0); //will throw NullPointerException
}catch(NullPointerException npe){
System.out.println("NESTED try-catch block handled - "
+ "NullPointerException");
}

}
}
}

Exception interview Question 18. Discuss which checked and unchecked exception can be thrown/declared by
subclass method while overriding superclass method in java?
Answer. Its very very important exception handling interview question. Experienced and freshers all must be able to
answer this question.

If superclass method throws/declare unchecked/RuntimeException in java >

overridden method of subclass can declare/throw any unchecked /RuntimeException (superclass or


subclass), or
overridden method of subclass cannot declare/throw any checked exception in java , or
overridden method of subclass can declare/throw same exception in java, or
overridden method of subclass may not declare/throw any exception in java.

12/23
If superclass method throws/declare checked/compileTime exception in java >

overridden method of subclass can declare/throw narrower (subclass of) checked exception, or
overridden method of subclass cannot declare/throw broader (superclass of) checked exception, or
overridden method of subclass can declare/throw any unchecked /RuntimeException, or
overridden method of subclass can declare/throw same exception, or
overridden method of subclass may not declare/throw any exception in java.

If superclass method does not throw/declare any exception in java >

overridden method of subclass can declare/throw any unchecked /RuntimeException , or


overridden method of subclass cannot declare/throw any checked exception, or
overridden method of subclass may not declare/throw any exception in java.

For programs please refer > Throw/declare checked and unchecked exception while overriding superclass method
in java

Exception interview Question 19. What will happen when catch and finally block both return value, also when try and
finally both return value in java?
Answer. This is very important exception handling interview question for experienced developers.

When catch and finally block both return value, method will ultimately return value returned by finally block
irrespective of value returned by catch block.

/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */


public class ExceptionTest {
public static void main(String[] args) {
System.out.println("method return -> " +m());
}

static String m(){


try{
int i=10/0; //will throw ArithmeticException
}catch(ArithmeticException e){
return "catch";
}finally{
return "finally";
}

}
}
/*OUTPUT
method return -> finally
*/

In above program, i=10/0 will throw ArithmeticException and enter catch block to return "catch", but ultimately
control will enter finally block to return "finally".

Likewise, when try and finally block both return value, method will ultimately return value returned by finally block

13/23
irrespective of value returned by try block. For program please refer.

Exception interview Question 20. What is exception propagation in java?


Answer.
Experienced developers must know in detail about Exception handling interview question in java. Even freshers
must try and understand this in depth concept of exception propagation in java.
Whenever methods are called stack is formed and an exception is first thrown from the top of the stack and if it is not
caught, it starts coming down the stack to previous methods until it is not caught.
If exception remains uncaught even after reaching bottom of the stack it is propagated to JVM and program is
terminated in java.

Propagating unchecked exception (NullPointerException) >


unchecked exceptions are automatically propagated in java.

stack of methods is formed >

14/23
In the above program, stack is formed and an exception is first thrown
from the top of the stack [ method3() ] and it remains uncaught there,
and starts coming down the stack to previous methods to method2(),
then to method1(), than to main() and it remains uncaught throughout.
exception remains uncaught even after reaching bottom of the stack [
main() ] so it is propagated to JVM and ultimately program is terminated
by throwing exception [ as shown in output ] in java.

Propagating checked exception (FileNotFoundException) using throws


keyword >
For propagating checked exceptions method must throw exception by
using throws keyword.

Exception interview Question 21. Can a catch or finally block throw exception in java?
Answer. Yes, catch or finally block can throw checked or unchecked exception but it must be handled accordingly.
Please refer this post for handling checked and unchecked exceptions in java.

Exception interview Question 22. Why shouldnt you use Exception for catching all exceptions in java?
Answer. Catching Exception rather than handling specific exception can be vulnerable to our application. Multiple
catch blocks must be used to catch specific exceptions, because handling specific exception gives developer the

15/23
liberty of taking appropriate action and develop robust application.

Exception interview Question 23. What is Difference between multiple catch block and multi catch syntax?
Answer. Experienced developers must know in detail about this Exception handling interview question in java

multiple catch block multi catch syntax

1 multiple catch blocks were introduced in prior multi catch syntax was introduced in java 7 for
versions of Java 7 and does not provide any improvements in multiple exception handling which
automatic resource management in java. helps in automatic resource management in java.

2 Here is the syntax for writing multiple catch Here is the multi catch syntax in java >
block in java >

try{ try{
//code . . . . . //code . . . . .
}catch(IOException ex1){ }catch(IOException | SQLException ex){
//code . . . . . //code . . . . .
} catch(SQLException ex2){ }
//code . . . . .
}
We could separate different exceptions using pipe ( | )

3 For catching IOException and SQLException with the help of multi catch syntax we can catch
we need to write two catch block like this > IOException and SQLException in one catch block using
multi catch syntax like this >

16/23
4 When multiple catch blocks are used , first If Multi catch syntax is used to catch subclass and its
catch block could be subclass of Exception superclass than compilation error will be thrown.
class handled in following catch blocks like this IOException and Exception in multi catch syntax will
> cause compilation error The exception IOException is
IOException is subclass of Exception in java. already caught by the alternative Exception.

Solution >
We must use only Exception to catch its subclass like
this >

5 Does not provide such features. Features of multi catch syntax >

Has improved way of catching multiple


exceptions.
This syntax does not looks clumsy.
Reduces developer efforts of writing multiple
catch blocks.
Allows us to catch more than one exception in
one catch block.
Helps in automatic resource management.

For more read : Difference between multiple catch block and multi catch syntax

Exception interview Question 24. can a method be overloaded on basis of exceptions in java ?
Answer.
Another Exception handling interview question which will test your practical understanding of exception in java.

17/23
Yes a method be overloaded on basis of exceptions in java.

But now question which overloaded exception will be called.


Lets take an example :
Ques. Let's say one method handles Exception and other handles ArithmeticException. Which method will be
invoked when ArithmeticException is thrown?
Ans. Method which handles more specific exception will be called.

Program >

import java.io.IOException;
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com
* Main class */
public class ExceptionTest {

void method(Exception e){


System.out.println(e+" caught in Exception method");
}
void method(ArithmeticException ae){
System.out.println(ae+" caught in ArithmeticException method" );
}

public static void main(String[] args) {


ExceptionTest obj=new ExceptionTest();
obj.method(new ArithmeticException());
obj.method(new IOException());
}
}
/* OUTPUT
java.lang.ArithmeticException caught in ArithmeticException method
java.io.IOException caught in Exception method
*/

Exception interview Question 25. Mention few exception handling best practices in java?
Answer. Experienced developers must be able to answer this Exception handling interview question in detail in java.

Throw exceptions when the method cannot handle the exception, and more importantly, must be handled by
the caller.

Example -
In Servlets - doGet() and doPost() throw ServletException or IOException in certain circumstances where the
request could not be read correctly. Neither of these methods are in a position to handle the exception, but the
container is (which generally results in the 404 error page in most cases).

Bubble the exception if the method cannot handle it. This is a corollary of the above point, but applicable to
methods that must catch the exception. If the caught exception cannot be handled correctly by the method,
then it is preferable to bubble it.

Throw the exception right away. If an exception scenario is encountered, then it is a good practice to throw
an exception indicating the original point of failure, instead of attempting to handle the failure via error codes,
until a point deemed suitable for throwing the exception. In other words, attempt to minimize mixing exception
handling with error handling.
18/23
Either log the exception or bubble it, but don't do both. Logging an exception often indicates that the
exception stack has been completely unwound, indicating that no further bubbling of the exception has
occurred. Hence, it is not recommended to do both at the same time, as it often leads to a frustrating
experience in debugging.

Application should not try to catch Error - Because, in most of cases recovery from an Error is almost
impossible. So, application must be allowed to terminate.

Example>
Lets say errors like OutOfMemoryError and StackOverflowError occur and are caught then JVM might not be able
to free up memory for rest of application to execute, so it will be better if application dont catch these errors and is
allowed to terminate.

Read : Complete list of Exception handling best practices and guidelines for using exceptions in java

Exception interview Question 26. Difference between Final, Finally and Finalize in java?
Answer. It is another very very important exception interview question to differentiate between final, finally and
finalize in java.

final finally finalize

1 final can be applied to variable, finally is a block. finalize is a method.


method and class in java.

2 try or try-catch block can be finalize method is called before garbage


2.1) Final variable followed by finally block > collection by JVM,
final memberVariable try-finally block, or finalize method is called for any
final local variable cleanup action that may be required
final static variable try{ before garbage collection.
//Code to be
Final memberVariable of class must enclosed in try-finally /** Copyright (c), AnkitMittal
be initialized at time of declaration, block JavaMadeSoEasy.com */
once initialized final memberVariable }finally{
cannot be assigned a new value. } @Override
Final variables are called constants protected void finalize()
in java. throws Throwable {
try-catch-finally block. try {
class FinalTest {
final int x=1; System.out.println("in
//memberVariable/instanceVariable try{ finalize() method, "
} //Code to be enclosed +
in try-catch-finally "doing cleanup activity");
block
}catch(Exception e){ } catch (Throwable
If constructor is defined then final }finally{
memberVariable can be initialized in throwable) {
} throw throwable;
constructor but once initialized
cannot be assigned a new value. }
}
finally block can can only
exist if try or try-catch block finalize() method is defined in
is there, finally block cant java.lang.Object
be used alone in java.
19/23
class FinalTest { finally block is not executed
final int x; in following scenarios >
//memberVariable/instanceVariable finally is not executed when
FinalTest() { System.exit is called.
x = 1; //final memberVariable if in case JVM crashes
can be initialized in constructor. because of some
} java.util.Error.
}

Final local variable can be left


uninitialized at time of declaration
and can be initialized later, but once
initialized cannot be assigned a new
value in java.

class FinalTest {
void method(){
final int x; //uninitialized at time
of declaration
x=1;
}
}

Final static variable of class must be


initialized at time of declaration or
can be initialized in static block, once
initialized final static variable cannot
be assigned a new value.

If static block is defined then final


static variable can be initialized in
static block, once initialized final
static variable cannot be assigned a
new value.

class FinalTest {
final static int x; //static variable
static{ //static block
x=1;
}
}

2.2) Final method


Final method cannot be overridden,
any attempt to do so will cause
compilation error.

Runtime polymorphism is not


applicable on final methods because
they cannot be inherited.

2.3) Final class


Final class cannot be extended, any
20/23
attempt to do so will cause
compilation error.

3 - finally block can only exist if We can force early garbage collection
try or try-catch block is in java by using following methods >
there, finally block cant be System.gc();
used alone in java. Runtime.getRuntime().gc();
System.runFinalization();
Runtime.getRuntime().runFinalization();

4 - finally is always executed If any uncaught exception is thrown


irrespective of exception inside finalize method -
thrown in java. exception is ignored,
thread is terminated and
object is discarded.

Note : Any exception thrown by the


finalize method causes the finalization
of this object to be halted, but is
otherwise ignored.

5 - Currently executing thread JVM does not guarantee which


calls finally method in java. daemon thread will invoke the finalize
method for an object.

6 final is a keyword in java. finally Is a keyword in java. finalize is not a keyword in java.

For more detail read : Final, Finally and Finalize - difference and similarity in java

Another Exception interview Question. What are the differences between between ClassNotFoundException and
NoClassDefFoundError in java ?

Answer.

ClassNotFoundException NoClassDefFoundError

1 ClassNotFoundException is Checked NoClassDefFoundError is a Error in


(compile time) Exception in java. java. Error and its subclasses are
regarded as unchecked exceptions in
java.

21/23
2 Here is the hierarchy of Here is the hierarchy of
java.lang.ClassNotFoundException - java.lang.NoClassDefFoundError -

-java.lang.Object -java.lang.Object
-java.lang.Throwable -java.lang.Throwable
-java.lang.Exception -java.lang.Error
-java.lang.ReflectiveOperationException -java.lang.LinkageError
-java.lang.ClassNotFoundException -java.lang.NoClassDefFoundError

3 ClassNotFoundException is thrown when NoClassDefFoundError is thrown when JVM


JVM tries to class from classpath but it does tries to load class which >
not find that class.
was NOT available at runtime but
was available at compile time.

ExceptionInInitializerError has got nothing to You must ensure that class does not throws
do with ClassNotFoundException. java.lang.ExceptionInInitializerError because
that is likely to be followed by
NoClassDefFoundError.

For more read differences between between ClassNotFoundException and NoClassDefFoundError in java

Another very important Exception interview Question. What are the most important frequently occurring Exception
and Errors which you faced in java?
Answer. Most common and frequently occurring checked (compile time) and Errors in java >

FileNotFoundException in java

SQLException in java

What is java.lang.InterruptedException in java

when java.lang.ClassNotFoundException occurs in java

Most common and frequently occurring unchecked (runtime) in java.

What is java.lang.NullPointerException in java, when it occurs,how to handle, avoid and


fix it

NumberFormatException in java

IndexOutOfBoundsException in java

When java.lang.ArrayIndexOutOfBoundsException occurs in java

When java.lang.StringIndexOutOfBoundsException occurs in java

java.lang.ArithmeticException in java - Divide number by zero

22/23
When dividing by zero does not throw ArithmeticException in java

When java.lang.IllegalStateException occurs in java

when java.lang.IllegalMonitorStateException is thrown in java

Solve java.lang.UnsupportedOperationException in java

Most common and frequently occurring Errors in java >

OutOfMemoryError in java

When java.lang.StackOverflowError occurs in java

Solve java.lang.ExceptionInInitializerError in java

How to solve java.lang.NoClassDefFoundError in java

For Q26- Q60 please read > 30 important OUTPUT questions Set-2

(JMSE.

23/23
EXCEPTIONS - Top 60 interview questions and answers in
java for fresher and experienced - 30 important OUTPUT
questions Set-2 > Q26- Q60
www.javamadesoeasy.com /2015/05/exceptions-top-60-interview-questions_75.html

You are here : Home / Core Java Tutorials / Java Interview Questions and answers

Time to impress interviewer, crack EXCEPTION interview questions in java. Best set of questions, your interview will
comprise of mostly these questions. I have tried to cover almost all the possible output questions which could be
framed in an interview.

First read : EXCEPTIONS - Top 60 interview questions and answers in java for fresher and
experienced - detailed explanation with diagrams Set-1 > Q1- Q25

Exception interview Question 26 .


Exception Output interview question 1.

public class MyClass {


static String str = "a";
public static void main(String[] args) {
new MyClass().method1();
System.out.println(str);
}
void method1() {
try {
method2();
} catch (Exception e) {
str += "b";
}
}
void method2() throws Exception {
try{
method3();
str += "c";
}catch(Exception e){
throw new Exception();
}finally{
str += "d";
}
method3();
str += "e";
}
void method3() throws Exception {
throw new Exception();
}
}
1/22
Answer. adb

Exception interview Question 27.


Exception Output interview question 2.

/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */


public class ExceptionTest {
public static void main(String[] args) {
m(); //call recursive method m()
System.out.println("Code after exception handling");
}

static void m() {


try {
m();
} catch (StackOverflowError e) {
e.printStackTrace();
}
}
}

Answer. method m() calls itself recursively so StackOverflowError will be thrown in java.

Output=
java.lang.StackOverflowError
at ExceptionTest.m(ExceptionTest.java:10)
.
.
.
.
.
.
.
.
Code after exception handling

Exception interview Question 28.


Exception Output interview question 3.

/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */


public class ExceptionTest {
public static void main(String[] args) {
int i=10/0;
System.out.println("Did this line execute?");
}
}
2/22
Answer. int i=10/0; will throw ArithmeticException in java
Output =
Exception in thread "main" java.lang.ArithmeticException: / by zero
At ExceptionTest.main(ExceptionTest.java:4)

Exception interview Question 29.


Exception Output interview question 4.

public class ExceptionTest {


public static void main(String[] args) {

try{
int i=10/0;
}catch(Exception e){
System.out.println("Exception handled properly in catch block");
}
System.out.println("Code after exception handling");
}
}

Answer.
int i=10/0; will throw ArithmeticException, Exception is superclass of ArithmeticException, so catch block will handle
ArithmeticException in java.

Output=
Exception handled properly
Code after exception handling

finally related output questions >

Exception interview Question 30.


Exception Output interview question 5.

public class ExceptionTest {


public static void main(String[] args) {

try{
int i=10/0; //will throw ArithmeticException
}catch(ArithmeticException e){
System.out.println("ArithmeticException handled in catch block");
}
finally{
System.out.println("finally block executed");
}
System.out.println("code after try-catch-finally block");
}
}

3/22
Answer. int i=10/0; will throw ArithmeticException, Exception is superclass of ArithmeticException, so catch block will
handle ArithmeticException and finally is always executed in java.

OUTPUT =
ArithmeticException handled in catch block
finally block executed
code after try-catch-finally block

Exception interview Question 31.


Exception Output interview question 6.

public class ExceptionTest {


public static void main(String[] args) {
try{
System.out.println("in try block");
System.exit(0);
}finally{
System.out.println("finally block executed");
}
}
}

Answer. finally block is not executed when System.exit is called in java.

OUTPUT =

in try block

Exception interview Question 32.


Exception Output interview question 7.

public class ExceptionTest {


public static void main(String[] args) {
try{
int i=10/0;
}catch(IndexOutOfBoundsException e){
System.out.println("IndexOutOfBoundsException handled in catch block");
}
finally{
System.out.println("finally block executed");
}
System.out.println("code after try-catch-finally block");
}
}

Answer. int i=10/0; will throw ArithmeticException, IndexOutOfBoundsException is not super class of
ArithmeticException, so catch block wont be able to handle ArithmeticException but finally is always executed in
4/22
java.

OUTPUT =
finally block executed
Exception in thread "main" java.lang.ArithmeticException: / by zero
at ExceptionTest.main(ExceptionTest.java:4)

Exception interview Question 33.


Exception Output interview question 8.

public class ExceptionTest {


public static void main(String[] args) {
System.out.println("method return -> " +m());
}

static String m(){


try{
int i=10/0;
}catch(ArithmeticException e){
return "catch";
}finally{
return "finally";
}

}
}

Answer. In above program, i=10/0 will throw ArithmeticException and enter catch block to return "catch", but
ultimately control will enter finally block to return "finally" in java.
OUTPUT =

method return -> finally

Multiple exception handling related output questions >

Exception handling interview Question 34.


Exception Output interview question 9.

5/22
public class ExceptionTest {
public static void main(String[] args) {

try{
int i=10/0;
}catch(ArithmeticException ae){
System.out.println("Exception handled - ArithmeticException" );
}catch(RuntimeException re){
System.out.println("Exception handled - RuntimeException");
}catch(Exception e){
System.out.println("Exception handled - Exception");
}
}
}

Answer. Yes, program will compile successfully in java.


In the above above >
i=10/0 will throw ArithmeticException and will be handled in first catch block.

ArithmeticException has been used in first catch block


RuntimeException has been used in second catch block
Exception has been used in third catch block

Exception is superclass of RuntimeException and


RuntimeException is superclass of ArithmeticException in java.

OUTPUT =
Exception handled - ArithmeticException

Exception handling interview Question 35.


Exception Output interview question 10.

public class ExceptionTest {


public static void main(String[] args) {
try{
int i=10/0;
}catch(Exception e){
System.out.println("Exception handled - RuntimeException");
}catch(ArithmeticException ae){
System.out.println("Exception handled - ArithmeticException" );
}
}
}

Answer. No, program will not compile.


Exception is superclass of ArithmeticException. Exception class handled in starting catch block must be subclass of
Exception class handled in following catch blocks (otherwise we will face compilation error) in java.

In above program we will compilation error at line 10


6/22
Exception handling interview Question 36.
Exception Output interview question 11.

public class MyClass {


static String s = "";

public static void main(String[] args) {


//try-catch-finally
try {
throw new Exception();
} catch (Exception e) {
//1st nested try-catch-finally
try {
//2nd nested try-catch-finally
try {
throw new Exception();
} catch (Exception ex) {
s += "a";
} finally{
s += "b";
}
throw new Exception();
} catch (Exception x) {
s += "c";
} finally {
s += "d";
}
} finally {
s += "e";
}
System.out.println(s);
}
}

Answer.
OUTPUT in java =
abcde

Exception handling interview Question 37.


7/22
Exception Output interview question 12 .

Answer. Exception is thrown at line 14, at that time value of str is abc
Output in java=
Exception in thread "main" java.lang.NullPointerException
at MyClass.method(MyClass.java:21)
at MyClass.main(MyClass.java:14)

Exception handling interview Question 38.


Exception Output interview question 13.

Answer. Yes, program will compile because UserDefinedException is RuntimeException and we are free not to
handle Runtime exceptions in java.

Output in java=
8/22
Exception in thread "main" UserDefinedException: user defined exception
at UserDefinedExceptionTest.main(UserDefinedExceptionTest.java:16)

Multi catch syntax related output questions in java >

Exception handling interview Question 39.


Exception Output interview question 14.
will this program compile?

import java.io.IOException;
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class ExceptionTest {
public static void main(String[] args) {
try{
throw new IOException();
}catch(IOException | Exception ex){
System.out.println(ex + " handled ");
}
}
}

Answer. No, program will not compile in java.


Multi catch syntax have been used in above program,
IOException is subclass of Exception in java.
if multi catch syntax is used to catch subclass and its superclass than compilation error will be thrown.
IOException and Exception in multi catch syntax will cause compilation error The exception IOException is already
caught by the alternative Exception.

Solution >
We must use only Exception to catch its subclass like this >

9/22
Propagating checked and unchecked exceptions related output questions in java >
Exception handling interview Question 40.
Exception Output interview question 15.

public class ExceptionTest {


public static void main(String[] args)
{
method1();
System.out.println("after calling m()");
}

static void method1(){


method2();
}

static void method2(){


method3();
}

static void method3(){


throw new NullPointerException();
}

Answer. unchecked exceptions are automatically propagated in java.

10/22
Exception handling interview Question 41.
Exception Output interview question 16.

public class ExceptionTest {


public static void main(String[] args)
throws FileNotFoundException {
method1();
System.out.println("after calling m()");
}

static void method1() throws FileNotFoundException{


method2();
}

static void method2() throws FileNotFoundException{


method3();
}

static void method3() throws FileNotFoundException{


throw new FileNotFoundException();
}

Answer. For propagating checked exceptions method must throw exception by using throws keyword in java.
11/22
Exception handling interview Question 42 .
Exception Output interview question 17.

Answer. Compilation of program will fail at line 21 because for propagating checked exceptions method must throw
exception by using throws keyword in java.

12/22
try-with-resource related output questions in java >

Exception handling interview Question 43.


Exception Output interview question 18.

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com
* Main class */
public class TryWithResourseTest {
public static void main(String[] args) throws IOException {
try (InputStream inputStream = new FileInputStream("c:/txtFile.txt")) {
//code...
}
}
}

Answer. Above program will execute properly provided file is found at specified directory. In java 7, using Try-with-
resources we need not to write explicit code for closing file in java.

Now, question comes why we need not to close file when we are using Try-with-resources?
Because FileInputStream implements java.lang.AutoCloseable interface (AutoCloseable interfaces close method
automatically closes resources which are no longer needed.) in java.

Exception handling interview Question 44.


Exception Output interview question 19.

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com
* Main class */
public class TryWithResourseTest {
public static void main(String[] args) throws IOException {
try (InputStream inputStream = new FileInputStream("c:/txtFile.txt") ;
InputStream bInputStream = new BufferedInputStream(inputStream) ) {
//code...
}
}
}

Answer. Above program will execute properly provided file is found at specified directory, Try-with-resources allows
us to use multiple resources inside it, all that we need to do is separate resources by semicolon (;)

throw and throws related output questions in java >

Exception handling interview Question 45.


13/22
Exception Output interview question 20.

import java.io.FileNotFoundException;
public class ExceptionTest {
public static void main(String[] args) {
m();
System.out.println("after calling m()");
}
static void m(){
throw new FileNotFoundException();
}
}

Answer. If checked Exception is not handled either by try-catch or throws, we will face compilation error in java.

Exception handling interview Question 46.


Exception Output interview question 21.

import java.io.FileNotFoundException;
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class ExceptionTest {
public static void main(String[] args) {
m();
System.out.println("after calling m()");
}
static void m(){
try {
throw new FileNotFoundException();
} catch (FileNotFoundException e) {
System.out.println("FileNotFoundException handled in try-catch block");
}
}
}

Answer. In above program, We throwed FileNotFoundException (checked exception) by using throw keyword and
handled it in try-catch block in java.

OUTPUT =

14/22
FileNotFoundException handled in try-catch block
after calling m()

Exception handling interview Question 47.


Exception Output interview question 22.

import java.io.FileNotFoundException;
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class ExceptionTest {
public static void main(String[] args) {
try {
m();
} catch (FileNotFoundException e) {
System.out.println("FileNotFoundException handled in try-catch block");
}
System.out.println("after calling m()");
}
static void m() throws FileNotFoundException{
throw new FileNotFoundException();
}
}

Answer. In the above program, method m() propagated exception to calling method (i.e. main method) using throws
in java.

OUTPUT of program =
FileNotFoundException handled in try-catch block
after calling m()

Exception handling interview Question 48.


Exception Output interview question 23.

Answer.
We throw NullPointerException (unChecked exception) and didnt handled it, no compilation error was thrown.
We need not to handle unChecked exception either by catching it or throwing it in java.

15/22
Output of program -

Exception handling interview Question 49.


Exception Output interview question 24.

Answer. We need to handle checked exception either by catching it or throwing it further, if not handled we will face
compilation error at line 8.

Exception handling interview Question 50.


Exception Output interview question 25.

import java.io.IOException;
import java.sql.SQLException;
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class ExceptionTest {
public static void main(String[] args) {
try {
m();
System.out.print("a");
} catch (Exception e) {
System.out.print("b");
} finally{
System.out.print("c");
}
}
static void m() throws IOException, SQLException{
int i=1;
if(i==1)
throw new IOException();
else
throw new SQLException();
}
}

Answer.
16/22
Output of program =
bc

Exception handling interview Question 51.


Exception Output interview question 26.

class SuperClass{
void method() throws NullPointerException{
System.out.println("superClass method");
}
}
class SubClass extends SuperClass{
void method() throws RuntimeException{
System.out.println("SubClass method");
}
}
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com
* Main class */
public class ExceptionTest {
public static void main(String[] args) {
SuperClass obj=new SubClass();
obj.method();
}
}

Answer. If superclass method does not throw/declare any exception - overridden method of subclass can
declare/throw any unchecked /RuntimeException (superclass or subclass) in java.

RuntimeException is superclass of NullPointerException.


Output of program =
SubClass method

Exception handling interview Question 52.


Exception Output interview question 27.

17/22
Answer. If superclass method does not throw/declare any exception - overridden method of subclass cannot
declare/throw any checked exception in java.

Any attempt to throw checked exception in overridden method of subclass will cause compilation error.

Exception handling interview Question 53.


Exception Output interview question 28.

import java.io.FileNotFoundException;
import java.io.IOException;
class SuperClass{
void method() throws IOException{
System.out.println("superClass method");
}
}
class SubClass extends SuperClass{
void method() throws FileNotFoundException{
System.out.println("SubClass method");
}
}
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com
* Main class */
public class ExceptionTest {
public static void main(String[] args) throws Exception {
SuperClass obj=new SubClass();
obj.method();
}
}

Answer. If superclass method throws/declare checked/compileTime exception - overridden method of subclass can
declare/throw narrower (subclass of) checked exception in java.

IOException is superclass of FileNotFoundException.


Output of program =
SubClass method

Exception handling interview Question 54.


Exception Output interview question 29.

18/22
Answer.
If superclass method throws/declare checked/compileTime exception - overridden method of subclass cannot
declare/throw broader (superclass of) checked exception in java.

Any attempt to throw broader (superclass of) checked exception in overridden method of subclass will cause
compilation error.
Exception is superclass of IOException in java.

Exception handling interview Question 55.


Exception Output interview question 30.

import java.io.IOException;
class SuperClass{
void method() throws IOException{
System.out.println("superClass method");
}
}
class SubClass extends SuperClass{
void method() throws NullPointerException{
System.out.println("SubClass method");
}
}
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com
* Main class */
public class ExceptionTest {
public static void main(String[] args) throws Exception {
SuperClass obj=new SubClass();
obj.method();
}
}

Answer. If superclass method throws/declare checked/compileTime exception - overridden method of subclass can
declare/throw any unchecked /RuntimeException in java.
Output of program =

SubClass method
19/22
Exception handling interview Question 56.
Exception Output interview question 31.

class SuperClass{
void method(){
System.out.println("superClass method");
}
}
class SubClass extends SuperClass{
void method() throws NullPointerException{
System.out.println("SubClass method");
}
}
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com
* Main class */
public class ExceptionTest {
public static void main(String[] args) throws Exception {
SuperClass obj=new SubClass();
obj.method();
}
}

Answer. If superclass method throws/declare unchecked/RuntimeException - overridden method of subclass can


declare/throw any unchecked /RuntimeException in java.

Output of program =
SubClass method

Exception handling interview Question 57.


Exception Output interview question 32.
Is it a valid method overriding program and if yes what will be output of program?

class SuperClass{
void method(){
System.out.println("superClass method");
}
}
class SubClass extends SuperClass{
void method() {
System.out.println("SubClass method");
}
}
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com
* Main class */
public class ExceptionTest {
public static void main(String[] args) throws Exception {
SuperClass obj=new SubClass();
obj.method();
}
}
20/22
Answer. Yes, Its a valid method overriding program.

/*OUTPUT of program
SubClass method
*/
If superclass method does not throw/declare any exception then overridden method of subclass may not
declare/throw any exception in java.

Exception handling interview Question 58.


Exception Output interview question 33.
Is it a valid method overriding program and if yes what will be output of program?

import java.io.FileNotFoundException;
import java.io.IOException;
class SuperClass{
void method() throws IOException{
System.out.println("superClass method");
}
}
class SubClass extends SuperClass{
void method(){
System.out.println("SubClass method");
}
}
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com
* Main class */
public class ExceptionTest {
public static void main(String[] args) throws Exception {
SuperClass obj=new SubClass();
obj.method();
}
}

Answer. Yes, Its a valid method overriding program.


/*OUTPUT of program
SubClass method
*/
If superclass method throws/declare checked/compileTime exception then overridden method of subclass may not
declare/throw any exception in java.

Exception handling interview Question 59.


Exception Output interview question 34.
Is it a valid method overriding program and if yes what will be output of program?

21/22
class SuperClass{
void method() throws NullPointerException{
System.out.println("superClass method");
}
}
class SubClass extends SuperClass{
void method(){
System.out.println("SubClass method");
}
}
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com
* Main class */
public class ExceptionTest {
public static void main(String[] args) {
SuperClass obj=new SubClass();
obj.method();
}
}

Answer. Yes, Its a valid method overriding program.

/*OUTPUT of program
SubClass method
*/

If superclass method throws/declare unchecked/RuntimeException overridden method of subclass may not


declare/throw any exception in java.

EXCEPTIONS - Top 60 interview questions and answers in java for fresher and experienced -
detailed explanation with diagrams Set-1 > Q1- Q25

Having any doubt? or you you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.

22/22

Potrebbero piacerti anche