Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
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.
unchecked exceptions
1/3
Exception propagation >
unchecked exceptions are automatically propagated in java.
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?
4 Creating
custom/own
exception class UserException extends class UserException extends
Exception { RuntimeException {
UserException(String s) { UserException(String s) {
super(s); super(s);
} }
} }
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?
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
Most common and frequently occurring checked (compile time) in java >
IOException in java
FileNotFoundException in java
SQLException in java
2/3
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
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
NumberFormatException in java
IndexOutOfBoundsException in java
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]
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
Must know :
ThreadDeath is an error which application must not try to catch but it is normal condition.
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");
}
RELATED LINKS>
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
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
try-catch block, or
try-finally block, or
try-catch-finally block.
try{
//Code to be enclosed in try-catch block
}catch(Exception e){
}
try{
//Code to be enclosed in try-finally block
}finally{
}
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
}
If any exception occurs and it is not handled properly, rest of the code is not executed >
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.
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 :
Program 5 to show what will happen when catch and finally both return some value.
Application of finally block in java programs >
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
}
Programming time - we will create following programs to demonstrate finally block in java >
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 5 to show what will happen when catch and finally both return some value.
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.
In the above program, finally block is not executed when System.exit is called.
4/5
Passing zero as parameter means normal termination &
Passing non-zero as parameter means abnormal termination.
Program 5 to show what will happen when catch and finally both return some value.
For Program 5, refer this post.
We may use finally block to execute code for database connection closing , because closing connection in try
or catch block may not be safe.
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 :
1/4
We throw NullPointerException (unChecked exception) and didnt handled it, no compilation error was thrown.
If checked Exception is not handled either by try-catch or throws, we will face compilation error.
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)
*/
method m() propagated exception to calling method (i.e. main method) using throws, and
main propagated exception to JVM using throws.
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 is written in methods definition to indicate that method can throw exception.
Above code throws NullPointerException (unChecked exception) and didnt handled it from where method m() was
called and no compilation error was thrown.
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.
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
Nested try-catch block means using try-catch block inside another try-catch block.
try{
int i=10/0; //will throw ArithmeticException
}catch(ArithmeticException ae){
System.out.println("try-catch block handled - ArithmeticException" );
}
}
}
/*OUTPUT
try-catch block handled - ArithmeticException
NESTED try-catch block handled - NullPointerException
*/
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
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.
try{
//code . . . . .
}catch(IOException ex1){
//code . . . . .
} catch(SQLException ex2){
//code . . . . .
}
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
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.
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.
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.
}
}
/*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());
}
}
}
/*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
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)
*/
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 :
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.
try{
//code . . . . .
}catch(IOException | SQLException ex){
//code . . . . .
}
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 >
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.)
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 (;)
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 :
Hi! In this post ill be explaining you in detail how checked and unchecked exceptions are 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 >
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 ].
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]
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 :
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
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.
2/9
1. Access modifier - Does not matter.
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)
3/9
6. final methods can be overloaded in java.
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 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
*/
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
When JVM loads MyClass it finds out main method with signature = [ public static void main(String[] args)].
6/9
char int, 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.
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.
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
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
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 :
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
overridden method of subclass may not declare/throw any exception (As shown in Program 8 - Newly added
on reader's request -).
overridden method of subclass may not declare/throw any exception. (As shown in Program 9 - Newly added
1/9
on reader's request).
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.
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) ..
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) .
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
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
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
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
*/
Program6 to show - overridden method of subclass can declare/throw any unchecked /RuntimeException
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
Any attempt to throw checked exception in overridden method of subclass will cause compilation error.
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
*/
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
*/
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
*/
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.
Ques. Let's say one method handles Exception and other handles ArithmeticException. Which method will be
invoked when ArithmeticException is thrown?
Program >
import java.io.IOException;
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com
* Main class */
public class ExceptionTest {
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.
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 .
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" );
}
}
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.
Java allows to use use try-catch block inside static initialization block.
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
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.
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
throw throws
1 throw keyword is used to throw an exception throws keyword is used to declare an exception.
explicitly.
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.
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.
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;
}
}
class FinalTest {
final static int x; //static variable
static{ //static block
x=1;
}
}
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();
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 >
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 >
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.
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
SQLException in java
NumberFormatException in java
IndexOutOfBoundsException in java
OutOfMemoryError 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.
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
ClassNotFoundException 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.
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.
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)
*/
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
*/
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
*/
NoClassDefFoundError is thrown when JVM tries to load class but no definition of class could be found.
4/8
C:\Users\ankitmittal01>e:
E:\>cd E:\workspace
E:\workspace>javac NoClassDefFoundErrorExample.java
E:\workspace>
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 >
We will create another simple program to understand how RuntimeException occured in static block of class can throw
NoClassDefFoundError.
5/8
package noClassDefFoundErrorPkg;
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" );
}
}
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
}
}
C:\Users\ankitmittal01>e:
E:\>cd E:\workspace
E:\workspace>javac NoClassDefFoundErrorExample.java
E:\workspace>
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 >
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 3. What are differences between checked and unchecked exceptions in java?
Answer. This is very important Exception handling interview question in java.
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);
} }
} }
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?
Read more on : Checked (compile time exceptions) and UnChecked (RuntimeExceptions) in java - Definition and
differences
finally finally block can can only exist if try or try-catch block is there, finally block cant be used alone
in java.
3/23
finally block is optional in java, we may use it or not.
throws throws is written in methods definition to indicate that method can throw exception 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.
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.
We throw NullPointerException (unChecked exception) and didnt handled it, no compilation error was thrown in
5/23
java.
throws is written in methods definition to indicate that method can throw exception.
Above code throws NullPointerException (unChecked exception) and didnt handled it from where method m() was
called and no compilation error was thrown.
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.
3 throw is always followed by instanceof Exception throws is always followed by name of Exception class in
class in java. java.
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.
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.
7/23
class UserDefinedException extends RuntimeException {
UserDefinedException(String s) {
super(s);
}
}
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.
try{
//Code to be enclosed in try-catch block
}catch(Exception e){
}
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.
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.
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
*/
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.
try{
//code . . . . .
}catch(IOException | SQLException ex){
//code . . . . .
}
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...
}
}
}
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.
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.
We may use finally block to execute code for database connection closing , because closing connection in try
or catch block may not be safe.
11/23
Because exception may be thrown in try block before reaching connection closing statement.
Nested try-catch block means using try-catch block inside another try-catch block in java.
try{
int i=10/0; //will throw ArithmeticException
}catch(ArithmeticException ae){
System.out.println("try-catch block handled - ArithmeticException" );
}
}
}
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.
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.
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.
}
}
/*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.
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.
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
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 >
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.
Program >
import java.io.IOException;
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com
* Main class */
public class ExceptionTest {
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.
class FinalTest {
void method(){
final int x; //uninitialized at time
of declaration
x=1;
}
}
class FinalTest {
final static int x; //static variable
static{ //static block
x=1;
}
}
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();
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
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
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
NumberFormatException in java
IndexOutOfBoundsException in java
22/23
When dividing by zero does not throw ArithmeticException in java
OutOfMemoryError 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 3. What are differences between checked and unchecked exceptions in java?
Answer. This is very important Exception handling interview question in java.
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);
} }
} }
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?
Read more on : Checked (compile time exceptions) and UnChecked (RuntimeExceptions) in java - Definition and
differences
finally finally block can can only exist if try or try-catch block is there, finally block cant be used alone
in java.
3/23
finally block is optional in java, we may use it or not.
throws throws is written in methods definition to indicate that method can throw exception 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.
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.
We throw NullPointerException (unChecked exception) and didnt handled it, no compilation error was thrown in
5/23
java.
throws is written in methods definition to indicate that method can throw exception.
Above code throws NullPointerException (unChecked exception) and didnt handled it from where method m() was
called and no compilation error was thrown.
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.
3 throw is always followed by instanceof Exception throws is always followed by name of Exception class in
class in java. java.
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.
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.
7/23
class UserDefinedException extends RuntimeException {
UserDefinedException(String s) {
super(s);
}
}
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.
try{
//Code to be enclosed in try-catch block
}catch(Exception e){
}
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.
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.
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
*/
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.
try{
//code . . . . .
}catch(IOException | SQLException ex){
//code . . . . .
}
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...
}
}
}
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.
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.
We may use finally block to execute code for database connection closing , because closing connection in try
or catch block may not be safe.
11/23
Because exception may be thrown in try block before reaching connection closing statement.
Nested try-catch block means using try-catch block inside another try-catch block in java.
try{
int i=10/0; //will throw ArithmeticException
}catch(ArithmeticException ae){
System.out.println("try-catch block handled - ArithmeticException" );
}
}
}
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.
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.
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.
}
}
/*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.
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.
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
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 >
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.
Program >
import java.io.IOException;
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com
* Main class */
public class ExceptionTest {
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.
class FinalTest {
void method(){
final int x; //uninitialized at time
of declaration
x=1;
}
}
class FinalTest {
final static int x; //static variable
static{ //static block
x=1;
}
}
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();
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
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
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
NumberFormatException in java
IndexOutOfBoundsException in java
22/23
When dividing by zero does not throw ArithmeticException in java
OutOfMemoryError 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
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
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
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
OUTPUT =
in try 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)
}
}
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 =
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");
}
}
}
OUTPUT =
Exception handled - ArithmeticException
Answer.
OUTPUT in java =
abcde
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)
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)
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 ");
}
}
}
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.
10/22
Exception handling interview Question 41.
Exception Output interview question 16.
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 >
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.
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 (;)
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.
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()
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()
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 -
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.
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
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.
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.
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.
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.
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();
}
}
Output of program =
SubClass method
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.
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();
}
}
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();
}
}
/*OUTPUT of program
SubClass method
*/
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