0% found this document useful (0 votes)
248 views110 pages

Exception Handling in Java

Exception handling in Java allows programs to continue running normally even if unexpected events occur by defining alternative flows, like catching a FileNotFoundException and using a local file instead of a remote one that is unavailable. Exceptions can be checked, which require the programmer to handle or declare them, or unchecked like NullPointerExceptions. Exception handling maintains the normal program flow when exceptions would otherwise disrupt it.

Uploaded by

Sajeev Paul
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
248 views110 pages

Exception Handling in Java

Exception handling in Java allows programs to continue running normally even if unexpected events occur by defining alternative flows, like catching a FileNotFoundException and using a local file instead of a remote one that is unavailable. Exceptions can be checked, which require the programmer to handle or declare them, or unchecked like NullPointerExceptions. Exception handling maintains the normal program flow when exceptions would otherwise disrupt it.

Uploaded by

Sajeev Paul
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 110

TechVeerendra’s

Software Solutions

Exception Handling in Java


What is Exception in Java?

Dictionary Meaning: Exception is an abnormal condition.

Exception: An unwanted unexpected event that disturbs normal flow of the


program is called exception.

It is an object which is thrown at runtime.

Example:

SleepingException

TyrePunchuredException

FileNotFoundException ...etc

 It is highly recommended to handle exceptions. The main objective of


exception handling is graceful (normal) termination of the program.

What is the meaning of exception handling?

Exception handling doesn't mean repairing an exception. We have to define


alternative way to continue rest of the program normally. This way of defining
alternative is nothing but exception handling.

Example:

Suppose our programming requirement is to read data from remote file locating
at London. At runtime if London file is not available then our program should
not be terminated normally.

We have to provide a local file to continue rest of the program normally. This
way of defining alternative is nothing but exception handling.

techveerendras@gmail.com
Ph: 9014424466 Page 1
TechVeerendra’s
Software Solutions

Example:

try

read data from London file

catch(FileNotFoundException e)

use local file and continue rest of the program normally

Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow of the
application. An exception normally disrupts the normal flow of the application
that is why we use exception handling.

1. statement 1;  
2. statement 2;  
3. statement 3;  
4. statement 4;  
5. statement 5;//exception occurs  
6. statement 6;  
7. statement 7;  
8. statement 8;  
9. statement 9;  
10. statement 10;  

techveerendras@gmail.com
Ph: 9014424466 Page 2
TechVeerendra’s
Software Solutions

Suppose there are 10 statements in your program and there occurs an


exception at statement 5, the rest of the code will not be executed i.e.
statement 6 to 10 will not be executed. If we perform exception handling, the
rest of the statement will be executed. That is why we use exception handling
in Java.

For every thread JVM will create a separate stack at the time of Thread
creation. All method calls performed by that thread will be stored in that stack.
Each entry in the stack is called "Activation record" (or) "stack frame".

After completing every method call JVM removes the corresponding entry from
the stack.

After completing all method calls JVM destroys the empty stack and terminates
the program normally.

Example:

class Test

public static void main(String[] args){

Wish();

public static void wish(){

greet();

public static void greet(){

System.out.println("Hello");

techveerendras@gmail.com
Ph: 9014424466 Page 3
TechVeerendra’s
Software Solutions

Output:

Hello

Default Exception Handling in Java:

 If an exception raised inside any method then that method is responsible


to create Exception object with the following information.

1. Name of the exception.

2. Description of the exception.

3. Location of the exception.(StackTrace)

 After creating that Exception object, the method handovers that object to
the JVM.
 JVM checks whether the method contains any exception handling code
or not. If method won't contain any handling code then JVM terminates
that method abnormally and removes corresponding entry form the
stack.

techveerendras@gmail.com
Ph: 9014424466 Page 4
TechVeerendra’s
Software Solutions

 JVM identifies the caller method and checks whether the caller method
contain any handling code or not. If the caller method also does not
contain handling code then JVM terminates that caller method also
abnormally and removes corresponding entry from the stack.
 This process will be continued until main() method and if the main()
method also doesn't contain any exception handling code then JVM
terminates main() method also and removes corresponding entry from
the stack.
 Then JVM handovers the responsibility of exception handling to the
default exception handler.
 Default exception handler just print exception information to the console
in the following format and terminates the program abnormally.

Exception in thread “xxx(main)” Name of exception: description

Location of exception (stack trace)

Example:

class Test

public static void main(String[] args){

wish();

public static void wish(){

greet();

public static void greet(){

System.out.println(10/0);

techveerendras@gmail.com
Ph: 9014424466 Page 5
TechVeerendra’s
Software Solutions

Output:

Exception in thread "main" java.lang.ArithmeticException: / by zero

atTest.greet(Test.java:10)

atTest.wish(Test.java:7)

atTest.main(Test.java:4)

Daigram:

Example:

class Test

public static void main(String[] args){

wish();

techveerendras@gmail.com
Ph: 9014424466 Page 6
TechVeerendra’s
Software Solutions

public static void wish(){

greet();

System.out.println(10/0);

public static void greet(){

System.out.println(“good morning”);

Example:

class Test

public static void main(String[] args){

wish();

System.out.println(10/0);

techveerendras@gmail.com
Ph: 9014424466 Page 7
TechVeerendra’s
Software Solutions

public static void wish(){

System.out.println(“Hi”);

public static void greet(){

System.out.println(“good morning”);

Note: In our program, if at least one method terminated abnormally the then
that program termination is abnormal termination.

If all methods terminated normally then only the program termination is


normal termination.

Hierarchy of Java Exception classes:

The java.lang.Throwable class is the root class of Java Exception hierarchy


which is inherited by two subclasses: Exception and Error.

techveerendras@gmail.com
Ph: 9014424466 Page 8
TechVeerendra’s
Software Solutions

Throwable acts as a root for exception hierarchy.

Throwable class contains the following two child classes.

Exception:

Most of the cases exceptions are caused by our program and these are
recoverable.

Ex: If FileNotFoundException occurs then we can use local file and we can
continue rest of the program execution normally.

Error:

Most of the cases errors are not caused by our program these are due to lack of
system resources and these are non-recoverable.

Ex: If OutOfMemoryError occurs being a programmer we can't do anything the


program will be terminated abnormally. System Admin or Server Admin is
responsible to raise/increase heap memory.

techveerendras@gmail.com
Ph: 9014424466 Page 9
TechVeerendra’s
Software Solutions

Types of Java Exceptions

There are mainly two types of exceptions: checked and unchecked. Here, an
error is considered as the unchecked exception. According to Oracle, there are
three types of exceptions:

1. Checked Exception

2. Unchecked Exception

3. Error

techveerendras@gmail.com
Ph: 9014424466 Page 10
TechVeerendra’s
Software Solutions

Checked Vs Unchecked Exceptions:

Checked exceptions: The exceptions which are checked by the compiler


whether programmer handling or not, for smooth execution of the program at
runtime, are called checked exceptions.

1. HallTicketMissingException

2. PenNotWorkingException

3. FileNotFoundException

Compiler will check whether we are handling checked exception or not.

If we are not handling then we will get compile time error.

Ex:

Import java.lang.*;

class Test

PrintWriter pw=new PrintWriter(abc.text);

Pw.println(“hello”);

Compile time: Unreported Exception java.io.FileNotFoundException; must be


caught or declared to thrown.

Note: In our program if there is chance of raising Checked Excption then


compulsory we should handle that checked exception either by using try-catch
or throws keyword. otherwise we will get compile time error.

Unchecked exceptions: The exceptions which are not checked by the compiler
whether programmer handing or not, are called unchecked exceptions.

techveerendras@gmail.com
Ph: 9014424466 Page 11
TechVeerendra’s
Software Solutions

1. BombBlastException

2. ArithmeticException

3. NullPointerException

Note: RuntimeException and its child classes, Error and its child classes are
unchecked and all the remaining are considered as checked exceptions.

Note: Whether exception is checked or unchecked compulsory it should occurs


at runtime only and there is no chance of occurring any exception at compile
time.

Difference between Checked and Unchecked Exceptions

1) Checked Exception

The classes which directly inherit Throwable class except RuntimeException


and Error are known as checked exceptions e.g. IOException, SQLException
etc. Checked exceptions are checked at compile-time.

2) Unchecked Exception

The classes which inherit RuntimeException are known as unchecked


exceptions e.g. ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked
at compile-time, but they are checked at runtime.

3) Error

Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError,


AssertionError etc.

techveerendras@gmail.com
Ph: 9014424466 Page 12
TechVeerendra’s
Software Solutions

Fully checked Vs Partially checked:

Fully checked: A checked exception is said to be fully checked if and only if all
its child classes are also checked.

Example:

1) IOException

2) InterruptedException

Partially checked: A checked exception is said to be partially checked if and


only if some of its child classes are unchecked.

Example:

Exception

Note: The only possible partially checked exceptions in java are:

1. Throwable.

2. Exception.

Q: Describe behavior of following exceptions?

1. RuntimeException-----unchecked

2. Error-----unchecked

3. IOException-----fully checked

4. Exception-----partially checked

5. InterruptedException-----fully checked

6. Throwable------partially checked

techveerendras@gmail.com
Ph: 9014424466 Page 13
TechVeerendra’s
Software Solutions

7. ArithmeticException ----- unchecked

8. NullPointerException ------ unchecked

9. FileNotFoundException ----- fully checked

Java Exception Keywords:

There are 5 keywords which are used in handling exceptions in Java.

Keywor Description
d

try The "try" keyword is used to specify a block where we should place
exception code. The try block must be followed by either catch or
finally. It means, we can't use try block alone.

catch The "catch" block is used to handle the exception. It must be preceded
by try block which means we can't use catch block alone. It can be
followed by finally block later.

finally The "finally" block is used to execute the important code of the
program. It is executed whether an exception is handled or not.

throw The "throw" keyword is used to throw an exception.

throws The "throws" keyword is used to declare exceptions. It doesn't throw an


exception. It specifies that there may occur an exception in the method.
It is always used with method signature.

techveerendras@gmail.com
Ph: 9014424466 Page 14
TechVeerendra’s
Software Solutions

Customized Exception Handling by using try-catch

 It is highly recommended to handle exceptions.


 In our program the code which may raise exception is called risky code;
we have to place risky code inside try block and the corresponding
handling code inside catch block.

Example:

try

Risky code

catch(Exception e)

Handling code

Without try catch:

class Test

public static void main(String[] args){

System.out.println("statement1");

System.out.println(10/0);

System.out.println("statement3");

techveerendras@gmail.com
Ph: 9014424466 Page 15
TechVeerendra’s
Software Solutions

output:

statement1

RE:AE:/by zero

at Test.main()

Abnormal termination.

With try catch:

class Test{

public static void main(String[] args){

System.out.println("statement1");

try{

System.out.println(10/0);

catch(ArithmeticException e){

System.out.println(10/2);

System.out.println("statement3");

}}

Output:

statement1

statement3

Normal termination.

techveerendras@gmail.com
Ph: 9014424466 Page 16
TechVeerendra’s
Software Solutions

Ex-2:

public class JavaExceptionExample{  

  public static void main(String args[]){  

   try{  

      //code that may raise exception  

      int data=100/0;  

   }

catch(ArithmeticException e){

System.out.println(e);

}  

   //rest code of the program   

   System.out.println("rest of the code...");  

  }  

Output:

Exception in thread main java.lang.ArithmeticException:/ by zero

rest of the code...

In the above example, 100/0 raises an ArithmeticException which is handled


by a try-catch block.

Java try-catch block

Java try block

Java try block is used to enclose the code that might throw an exception. It
must be used within the method.

techveerendras@gmail.com
Ph: 9014424466 Page 17
TechVeerendra’s
Software Solutions

Java try block must be followed by either catch or finally block.

Syntax of java try-catch

try{  

//code that may throw exception  

catch(Exception_class_Name ref){

}  

Syntax of try-finally block

try{  

//code that may throw exception  

finally{

}  

Java catch block

Java catch block is used to handle the Exception. It must be used after the try
block only.

You can use multiple catch block with a single try.

Problem without exception handling:

public class Testtrycatch1{  

  public static void main(String args[]){  

      int data=50/0;//may throw exception  

      System.out.println("rest of the code...");  

}  

}  

techveerendras@gmail.com
Ph: 9014424466 Page 18
TechVeerendra’s
Software Solutions

Output:

Exception in thread main java.lang.ArithmeticException:/ by zero

Solution by exception handling:

public class Testtrycatch2{  

  public static void main(String args[]){  

   try{  

      int data=50/0;  

   }catch(ArithmeticException e){System.out.println(e);}  

   System.out.println("rest of the code...");  

}  

}  

Output:

Exception in thread main java.lang.ArithmeticException:/ by zero

rest of the code...

techveerendras@gmail.com
Ph: 9014424466 Page 19
TechVeerendra’s
Software Solutions

Internal working of java try-catch block:

The JVM firstly checks whether the exception is handled or not. If exception is
not handled, JVM provides a default exception handler that performs the
following tasks:

o Prints out exception description.

o Prints the stack trace (Hierarchy of methods where the exception


occurred).

o Causes the program to terminate.

But if exception is handled by the application programmer, normal flow of the


application is maintained i.e. rest of the code is executed.

techveerendras@gmail.com
Ph: 9014424466 Page 20
TechVeerendra’s
Software Solutions

Control flow in try catch:

try{

statement-1;

statement-2;

statement-3;

catch(X e) {

statement-4;

statement5;

Case 1: If there is no exception.

1, 2, 3, 5 normal termination.

public class JavaExceptionExample{

public static void main(String args[]){

System.out.println("start of the code...");

try{

System.out.println("s1...");

System.out.println("s2");

System.out.println("s3");

//code that may raise exception

//int data=100/0;

techveerendras@gmail.com
Ph: 9014424466 Page 21
TechVeerendra’s
Software Solutions

catch(ArithmeticException e){

System.out.println("s4");

//rest code of the program

System.out.println("s5");

Case 2: if an exception raised at statement 2 and corresponding catch block


matched.

1, 4, 5 normal termination.

public class JavaExceptionExample{

public static void main(String args[]){

System.out.println("start of the code...");

try{

System.out.println("s1...");

System.out.println(10/0);

System.out.println("s3");

//code that may raise exception

techveerendras@gmail.com
Ph: 9014424466 Page 22
TechVeerendra’s
Software Solutions

//int data=100/0;

catch(ArithmeticException e){

System.out.println(e);

//rest code of the program

System.out.println("s5");

Case 3: if an exception raised at statement 2 but the corresponding catch


block not matched.

1 followed by abnormal termination.

public class JavaExceptionExample{

public static void main(String args[]){

System.out.println("start of the code...");

try{

System.out.println("s1...");

System.out.println(10/0);

System.out.println("s3");

//code that may raise exception

techveerendras@gmail.com
Ph: 9014424466 Page 23
TechVeerendra’s
Software Solutions

//int data=100/0;

catch(NullPointerException e){

System.out.println(e);

//rest code of the program

System.out.println("s5");

}
Case 4: if an exception raised at statement 4 or statement 5 then it's always
abnormal termination of the program.

public class JavaExceptionExample{

public static void main(String args[]){

System.out.println("start of the code...");

try{

System.out.println("s1...");

System.out.println(10/0);

System.out.println("s3");

//code that may raise exception

//int data=100/0;

techveerendras@gmail.com
Ph: 9014424466 Page 24
TechVeerendra’s
Software Solutions

catch(ArithmeticException e){

System.out.println(e);

System.out.println(10/0);

//rest code of the program

System.out.println("s5");

Note:

 Within the try block if anywhere an exception raised then rest of the try
block won't be executed even though we handled that exception. Hence
we have to place/take only risk code inside try block and length of the
try block should be as less as possible.
 If any statement which raises an exception and it is not part of any try
block then it is always abnormal termination of the program.
 There may be a chance of raising an exception inside catch and finally
blocks also in addition to try block.

Various methods to print exception information:

Throwable class defines the following methods to print exception information to


the console.

printStackTrace():

techveerendras@gmail.com
Ph: 9014424466 Page 25
TechVeerendra’s
Software Solutions

This method prints exception information in the following format.

Name of the exception: description of exception

Stack trace

toString(): This method prints exception information in the following format.

Name of the exception: description of exception

getMessage(): This method returns only description of the exception.

Description

Example:

Note: Default exception handler internally uses printStackTrace() method to


print exception information to the console.

Try with multiple catch blocks:

techveerendras@gmail.com
Ph: 9014424466 Page 26
TechVeerendra’s
Software Solutions

The way of handling an exception is varied from exception to exception. Hence


for every exception type it is recommended to take a separate catch block. That
is try with multiple catch blocks is possible and recommended to use.

Example:

try

catch(Exception e)

default handler

Ex:

public class TestMultipleCatchBlock{

public static void main(String args[]){

try{

int a[]=new int[5];

a[5]=30/0;

catch(Exception e){

System.out.println("task1 is completed");

techveerendras@gmail.com
Ph: 9014424466 Page 27
TechVeerendra’s
Software Solutions

Note: This approach is not recommended because for any type of Exception we
are using the same catch block.

With multiple catch:

try

catch(FileNotFoundException e)

use local file

catch(ArithmeticException e)

perform these Arithmetic operations

catch(SQLException e)

don't use oracle db, use mysqldb

catch(Exception e)

default handler

techveerendras@gmail.com
Ph: 9014424466 Page 28
TechVeerendra’s
Software Solutions

Ex:

public class TestMultipleCatchBlock{  

  public static void main(String args[]){  

   try{  

    int a[]=new int[5];  

    a[5]=30/0;  

   }  

   catch(ArithmeticException e){

System.out.println("task1 is completed");

}  

   catch(ArrayIndexOutOfBoundsException e){

System.out.println("task 2 completed");

}  

   catch(Exception e){

System.out.println("common task completed");

}  

   System.out.println("rest of the code...");  

  }  

}  

Note: This approach is highly recommended because for any exception raise
we are defining a separate catch block.

Note: At a time only one Exception is occured and at a time only one catch
block is executed.

techveerendras@gmail.com
Ph: 9014424466 Page 29
TechVeerendra’s
Software Solutions

Rule: If try with multiple catch blocks present then order of catch blocks is
very important. It should be from child to parent by mistake if we are taking
from parent to child then we will get Compile time error saying

"exception xxx has already been caught"

Ex-Order of Parent to child:

class Test

public static void main(String[] args)

try

System.out.println(10/0);

catch(Exception e)

e.printStackTrace();

catch(ArithmeticException e)

e.printStackTrace();

}}}

CE: Exception

java.lang.ArithmeticException has already been caught

techveerendras@gmail.com
Ph: 9014424466 Page 30
TechVeerendra’s
Software Solutions

Ex- Order of Child to Parent:

class Test

public static void

main(String[] args)

try

System.out.println(10/0);

catch(ArithmeticException e)

e.printStackTrace();

catch(Exception e)

e.printStackTrace();

}}}

Output:

Compile successfully.

techveerendras@gmail.com
Ph: 9014424466 Page 31
TechVeerendra’s
Software Solutions

Ex-2:

class TestMultipleCatchBlock1{  

  public static void main(String args[]){  

   try{  

    int a[]=new int[5];  

    a[5]=30/0;  

   }  

   catch(Exception e){

System.out.println("common task completed");

}  

   catch(ArithmeticException e){

System.out.println("task1 is completed");

}  

   catch(ArrayIndexOutOfBoundsException e){

System.out.println("task 2 completed");

}  

   System.out.println("rest of the code...");  

 }  

}  

Output:

Compile-time error

techveerendras@gmail.com
Ph: 9014424466 Page 32
TechVeerendra’s
Software Solutions

Note: if we are trying to take multiple catch blocks same type exceptions then
we will get compile time error.

Ex:

try

catch(AE e)

catch(AE e)

Java finally block


 Java finally block is a block that is used to execute important code such
as closing connection, stream etc.

techveerendras@gmail.com
Ph: 9014424466 Page 33
TechVeerendra’s
Software Solutions

 Java finally block is always executed whether exception is handled or


not.
 Java finally block follows try or catch block.
 It is not recommended to take clean up code inside try block because
there is no guarantee for the execution of every statement inside a try.
 It is not recommended to place clean up code inside catch block because
if there is no exception then catch block won't be executed.
 We require some place to maintain clean up code which should be
executed always irrespective of whether exception raised or not raised
and whether handled or not handled. Such type of best place is nothing
but finally block.
 Hence the main objective of finally block is to maintain cleanup code.

Example:

try

risky code

catch(x e)

handling code

finally

techveerendras@gmail.com
Ph: 9014424466 Page 34
TechVeerendra’s
Software Solutions

cleanup code

The speciality of finally block is it will be executed always irrespective of


whether the exception raised or not raised and whether handled or not
handled.

Note: If you don't handle exception, before terminating the program, JVM
executes finally block (if any).

Why use java finally?

techveerendras@gmail.com
Ph: 9014424466 Page 35
TechVeerendra’s
Software Solutions

o Finally block in java can be used to put "cleanup" code such as closing a
file, closing connection etc.

Case-1: If there is no Exception:

class Test

public static void main(String[] args)

try

System.out.println("try block executed");

catch(ArithmeticException e)

System.out.println("catch block executed");

finally

System.out.println("finally block executed");

Output:

try block executed

Finally block executed

Ex-2:

techveerendras@gmail.com
Ph: 9014424466 Page 36
TechVeerendra’s
Software Solutions

class TestFinallyBlock{  

  public static void main(String args[]){  

  try{  

   int data=25/5;  

   System.out.println(data);  

  }  

  catch(NullPointerException e){

System.out.println(e);

}  

  finally{

System.out.println("finally block is always executed");

}  

  System.out.println("rest of the code...");  

  }  

}  

Output: 5

finally block is always executed

rest of the code..

Case-2: If an exception raised but the corresponding catch block matched:

class Test

public static void main(String[] args)

try

techveerendras@gmail.com
Ph: 9014424466 Page 37
TechVeerendra’s
Software Solutions

System.out.println("try block executed");

System.out.println(10/0);

catch(ArithmeticException e)

System.out.println("catch block executed");

finally

System.out.println("finally block executed");

Output:

Try block executed

Catch block executed

Finally block executed

Ex-2:

class TestFinallyBlock1{  

  public static void main(String args[]){  

  try{  

   int data=25/0;  

   System.out.println(data);  

  }  

techveerendras@gmail.com
Ph: 9014424466 Page 38
TechVeerendra’s
Software Solutions

  catch(NullPointerException e){

System.out.println(e);

}  

  finally{

System.out.println("finally block is always executed");

}  

  System.out.println("rest of the code...");  

  }  

}  

Output:

finally block is always executed

Exception in thread main java.lang.ArithmeticException:/ by zero

Case-3: If an exception raised but the corresponding catch block not


matched:

class Test

public static void main(String[] args)

try

System.out.println("try block executed");

System.out.println(10/0);

catch(NullPointerException e)

techveerendras@gmail.com
Ph: 9014424466 Page 39
TechVeerendra’s
Software Solutions

System.out.println("catch block executed");

finally

System.out.println("finally block executed");

Output:

Try block executed

Finally block executed

Exception in thread "main" java.lang.ArithmeticException: / by zero

atTest.main(Test.java:8)

Ex:

public class TestFinallyBlock2{  

  public static void main(String args[]){  

  try{  

   int data=25/0;  

   System.out.println(data);  

  }  

  catch(ArithmeticException e){System.out.println(e);}  

  finally{System.out.println("finally block is always executed");}  

  System.out.println("rest of the code...");  

  }  

techveerendras@gmail.com
Ph: 9014424466 Page 40
TechVeerendra’s
Software Solutions

}  

Output:Exception in thread main java.lang.ArithmeticException:/ by zero

finally block is always executed

rest of the code...

Rule: For each try block there can be zero or more catch blocks, but only one
finally block.

return Vs finally:

Even though return statement present in try or catch blocks first finally will be
executedand after that only return statement will be considered. i.efinally block
dominates return statement.

Example:

class Test

public static void main(String[] args)

try

System.out.println("try block executed");

return;

catch(ArithmeticException e)

System.out.println("catch block executed");

finally

techveerendras@gmail.com
Ph: 9014424466 Page 41
TechVeerendra’s
Software Solutions

System.out.println("finally block executed");

}}

Output:

try block executed

Finally block executed

Note: If return statement present try, catch and finally blocks then finally
block return statement will be considered.

Example:

class Test

public static void main(String[] args)

System.out.println(m1());

public static intm1(){

try

System.out.println(10/0);

return 777;

catch(ArithmeticException e)

return 888;

techveerendras@gmail.com
Ph: 9014424466 Page 42
TechVeerendra’s
Software Solutions

finally{

return 999;

}}

Output:

999

finally vs System.exit(0):

There is only one situation where the finally block won't be executed is
whenever we are using System.exit(0) method.

Whenever we are using System.exit(0) then JVM itself will be shutdown , in this
case finally block won't be executed.

i.e., System.exit(0) dominates finally block.

Example:

class Test

public static void main(String[] args)

try

System.out.println("try");

System.exit(0);

catch(ArithmeticException e)

techveerendras@gmail.com
Ph: 9014424466 Page 43
TechVeerendra’s
Software Solutions

System.out.println("catch block executed");

finally

System.out.println("finally block executed");

}}

Output:

try

Note : System.exit(0);

 This argument acts as status code. Insteadof zero, we can take any
integer value
 Zero means normal termination , non-zero means abnormal termination
 This status code internally used by JVM, whether it is zero or non-zero
there is no change in the result and effect is same wrt program.

Difference between final, finally, and finalize:

final:

 final is the modifier applicable for classes, methods and variables.


 If a class declared as the final then child class creation is not possible.
 If a method declared as the final then overriding of that method is not
possible.
 If a variable declared as the final then reassignment is not possible.

finally:

techveerendras@gmail.com
Ph: 9014424466 Page 44
TechVeerendra’s
Software Solutions

finally is the block always associated with try-catch to maintain clean up code
which should be executed always irrespective of whether exception raised or
not raised and whether handled or not handled.

finalize:

finalize is a method, always invoked by Garbage Collector just before destroying


an object to perform cleanup activities.

Note:

 finally block meant for cleanup activities related to try block where as
finalize() method meant for cleanup activities related to object.
 To maintain clean up code finally block is recommended over finalize()
method because we can't expect exact behavior of GC.

Java final example

class FinalExample{  

public static void main(String[] args){  

final int x=100;  

x=200;//Compile Time Error  

}}  

Java finally example

class FinallyExample{  

public static void main(String[] args){  

try{  

int x=300;  

techveerendras@gmail.com
Ph: 9014424466 Page 45
TechVeerendra’s
Software Solutions

}catch(Exception e){System.out.println(e);}  

finally{System.out.println("finally block is executed");}  

}}  

Java finalize example

class FinalizeExample{  

public void finalize(){System.out.println("finalize called");}  

public static void main(String[] args){  

FinalizeExample f1=new FinalizeExample();  

FinalizeExample f2=new FinalizeExample();  

f1=null;  

f2=null;  

System.gc();  

}}  

Control flow in try catch finally:

Ex:

try

Stmt 1;

Stmt-2;

Stmt-3;

techveerendras@gmail.com
Ph: 9014424466 Page 46
TechVeerendra’s
Software Solutions

catch(Exception e)

Stmt-4;

finally

stmt-5;

Stmt-6;

Case 1: If there is no exception. 1, 2, 3, 5, 6 normal termination.

Case 2: if an exception raised at statement 2 and corresponding catch block


matched. 1,4,5,6 normal terminations.

Case 3: if an exception raised at statement 2 and corresponding catch block is


not matched. 1,5 abnormal termination.

Case 4: if an exception raised at statement 4 then it's always abnormal


termination but before the finally block will be executed.

Case 5: if an exception raised at statement 5 or statement 6 its always


abnormal termination.

Control flow in Nested try-catch-finally:

The try block within a try block is known as nested try block in java.

Why use nested try block

techveerendras@gmail.com
Ph: 9014424466 Page 47
TechVeerendra’s
Software Solutions

Sometimes a situation may arise where a part of a block may cause one error
and the entire block itself may cause another error. In such cases, exception
handlers have to be nested.

Syntax:

....  

try  

{  

    statement 1;  

    statement 2;  

    try  

    {  

        statement 1;  

        statement 2;  

    }  

    catch(Exception e)  

    {  

    }  

}  

catch(Exception e)  

{  

}  

....  

Ex:

techveerendras@gmail.com
Ph: 9014424466 Page 48
TechVeerendra’s
Software Solutions

class Excep6{  

 public static void main(String args[]){  

  try{  

    try{  

     System.out.println("going to divide");  

     int b =39/0;  

    }catch(ArithmeticException e){System.out.println(e);}  

   

    try{  

    int a[]=new int[5];  

    a[5]=4;  

    }catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}  

     

    System.out.println("other statement);  

  }catch(Exception e){System.out.println("handeled");}  

  

  System.out.println("normal flow..");  

 }  

}  

Control flow in Nested try-catch-finally:

try

stmt-1;

stmt-2;

stmt-3;

techveerendras@gmail.com
Ph: 9014424466 Page 49
TechVeerendra’s
Software Solutions

try

stmt-4;

stmt-5;

stmt-6;

catch (X e)

stmt-7;

finally

stmt-8;

stmt-9;

catch (Y e)

stmt-10;

finally

stmt-11;

stmt-12;

techveerendras@gmail.com
Ph: 9014424466 Page 50
TechVeerendra’s
Software Solutions

Case 1: if there is no exception. 1, 2, 3, 4, 5, 6, 8, 9, 11, 12 normalm


termination.

Case 2: if an exception raised at statement 2 and corresponding catch block


matched 1,10,11,12 normal terminations.

Case 3: if an exception raised at statement 2 and corresponding catch block is


not matched 1, 11 abnormal termination.

Case 4: if an exception raised at statement 5 and corresponding inner catch


has matched 1, 2, 3, 4, 7, 8, 9, 11, 12 normal termination.

Case 5: if an exception raised at statement 5 and inner catch has not matched
but outer catch block has matched. 1, 2, 3, 4, 8, 10, 11, 12 normal
termination.

Case 6: if an exception raised at statement 5 and both inner and outer catch
blocks are not matched. 1, 2, 3, 4, 8, 11 abnormal termination.

Case 7: if an exception raised at statement 7 and the corresponding catch


block matched 1, 2, 3, 4, 5, 6, 8, 10, 11, 12 normal termination.

Case 8: if an exception raised at statement 7 and the corresponding catch


block not matched 1, 2, 3, 4, 5, 6, 8, 11 abnormal terminations.

Case 9: if an exception raised at statement 8 and the corresponding catch


block has matched 1, 2, 3, 4, 5, 6, 7, 10, 11,12 normal termination.

Case 10: if an exception raised at statement 8 and the corresponding catch


block not matched 1, 2, 3, 4, 5, 6, 7, 11 abnormal terminations.

Case 11: if an exception raised at statement 9 and corresponding catch block


matched 1, 2, 3, 4, 5, 6, 7, 8,10,11,12 normal termination.

techveerendras@gmail.com
Ph: 9014424466 Page 51
TechVeerendra’s
Software Solutions

Case 12: if an exception raised at statement 9 and corresponding catch block


not matched 1, 2, 3, 4, 5, 6, 7, 8, 11 abnormal termination.

Case 13: if an exception raised at statement 10 is always abnormal


termination but before that finally block 11 will be executed.

Case 14: if an exception raised at statement 11 or 12 is always abnormal


termination.

Note:

 If we are not entering into the try block then the finally block won't be
executed. Once we entered into the try block without executing finally
block we can't come out.
 We can take try-catch inside try i.e., nested try-catch is possible
 The most specific exceptions can be handled by using inner try-catch
and generalized exceptions can be handle by using outer try-catch.

Example:

class Test

public static void main(String[] args){

try{

System.out.println(10/0);

catch(ArithmeticException e)

System.out.println(10/0);

techveerendras@gmail.com
Ph: 9014424466 Page 52
TechVeerendra’s
Software Solutions

finally{

String s=null;

System.out.println(s.length());

}}

output :

RE:NullPointerException

Note: Default exception handler can handle only one exception at a time and
that is the most recently raised exception.

Various possible combinations of try catch finally:

 Whenever we are writing try block compulsory we should write either


catch or finally. i.e., try without catch or finally is invalid.
 Whenever we are writing catch block compulsory we should write try.
i.e., catch without try is invalid.
 Whenever we are writing finally block compulsory we should write try.
i.e., finally without try is invalid.
 In try-catch-finally order is important.
 Within the try-catch -finally blocks we can take try-catch-finally. i.e.,
nesting of try-catch-finally is possible.
 For try-catch-finally blocks curly braces are mandatory.

techveerendras@gmail.com
Ph: 9014424466 Page 53
TechVeerendra’s
Software Solutions

techveerendras@gmail.com
Ph: 9014424466 Page 54
TechVeerendra’s
Software Solutions

techveerendras@gmail.com
Ph: 9014424466 Page 55
TechVeerendra’s
Software Solutions

techveerendras@gmail.com
Ph: 9014424466 Page 56
TechVeerendra’s
Software Solutions

Java throw exception:

Java throw keyword

The Java throw keyword is used to explicitly throw an exception.

We can throw either checked or uncheked exception in java by throw keyword.


The throw keyword is mainly used to throw custom exception.

techveerendras@gmail.com
Ph: 9014424466 Page 57
TechVeerendra’s
Software Solutions

Syntax of java throw keyword:

throw exception; 

Example of throw IOException.

throw new IOException("sorry device error);  

Ex: without using throw:

class Test

public static void main(String[] args){

System.out.println(10/0);

}}

In this case creation of ArithmeticException object and handover to the jvm will
be performed automatically by the main() method.

Ex- using throw keyword:

class Test

public static void main(String[] args){

throw new ArithmeticException("/by zero");

techveerendras@gmail.com
Ph: 9014424466 Page 58
TechVeerendra’s
Software Solutions

}}

In this case we are creating exception object explicitly and handover to the JVM
manually.

Ex:

We have created the validate method that takes integer value as a parameter. If
the age is less than 18, we are throwing the ArithmeticException otherwise
print a message welcome to vote.

public class TestThrow1{  

   static void validate(int age){  

     if(age<18)  

      throw new ArithmeticException("not valid");  

     else  

      System.out.println("welcome to vote");  

   }  

   public static void main(String args[]){  

      validate(13);  

      System.out.println("rest of the code...");  

  }  

}  

Output:

Exception in thread main java.lang.ArithmeticException:not valid.

techveerendras@gmail.com
Ph: 9014424466 Page 59
TechVeerendra’s
Software Solutions

Ex:

class Test3

static ArithmeticException e=new ArithmeticException();

public static void main(String[]args){

throw e;

Output:

Runtime exception: Exception in thread "main" java.lang.ArithmeticException

Ex:

class Test3

static ArithmeticException e;// not referring any object

public static void main(String[] args){

throw e;

Output:

techveerendras@gmail.com
Ph: 9014424466 Page 60
TechVeerendra’s
Software Solutions

Exception in thread "main" java.lang.NullPointerException at


Test3.main(Test3.java:5)

Case 2:

After throw statement we can't take any statement directly otherwise we will
get compile time error saying unreachable statement.

Ex:

class Test3

public static void main(String[] args){

System.out.println(10/0);

System.out.println("hello");

Output:

Runtime error: Exception in thread "main" java.lang.ArithmeticException: / by


zero

at Test3.main(Test3.java:4)

Ex:

class Test3

public static void main(String[] args){

throw new ArithmeticException("/ by zero");

System.out.println("hello");

techveerendras@gmail.com
Ph: 9014424466 Page 61
TechVeerendra’s
Software Solutions

Output:

Compile time error.

Test3.java:5: unreachable statement System.out.println("hello");

Case 3:

We can use throw keyword only for Throwable types otherwise we will get
compile time error saying incomputable types.

Ex:

class Test3

public static void main(String[] args){

throw new Test3();

Output:

Compile time error.

Test3.java:4: incompatible types

found : Test3

required: java.lang.Throwable

throw new Test3();

Ex:

class Test3 extends RuntimeException

public static void main(String[] args){

throw new Test3();

techveerendras@gmail.com
Ph: 9014424466 Page 62
TechVeerendra’s
Software Solutions

Output:

Runtime error: Exception in thread "main" Test3

at Test3.main(Test3.java:4)

Throws statement
In our program if there is any chance of raising checked exception then
compulsory we should handle either by try catch or by throws keyword
otherwise the code won't compile.

Example:

import java.io.*;

class Test3

public static void main(String[] args){

PrinterWriter out=new PrintWriter("abc.txt");

out.println("hello");

CE :

Unreported exception java.io.FileNotFoundException; must be caught or


declared to be thrown.

techveerendras@gmail.com
Ph: 9014424466 Page 63
TechVeerendra’s
Software Solutions

Example:

class Test3

public static void main(String[] args){

Thread.sleep(5000);

Unreported exception java.lang.InterruptedException; must be caught or


declared to be thrown.

The Java throws keyword is used to declare an exception. It gives an


information to the programmer that there may occur an exception so it is
better for the programmer to provide the exception handling code so that
normal flow can be maintained.

Exception Handling is mainly used to handle the checked exceptions. If there


occurs any unchecked exception such as NullPointerException, it is
programmers fault that he is not performing check up before the code being
used.

Syntax of java throws

return_type method_name() throws exception_class_name{  

//method code  

}  

Which exception should be declared

techveerendras@gmail.com
Ph: 9014424466 Page 64
TechVeerendra’s
Software Solutions

Ans) checked exception only, because:

o unchecked Exception: under your control so correct your code.

o error: beyond your control e.g. you are unable to do anything if there


occurs VirtualMachineError or StackOverflowError.

Advantage of Java throws keyword

Now Checked Exception can be propagated (forwarded in call stack).

It provides information to the caller of the method about the exception.

We can handle this compile time error by using the following 2 ways.

By using try catch:

class Test3

public static void

main(String[] args){

try{

Thread.sleep(5000);

catch(InterruptedException e){

Output:

Compile and running

Successfully

techveerendras@gmail.com
Ph: 9014424466 Page 65
TechVeerendra’s
Software Solutions

By using throws keyword:

We can use throws keyword to delegate the responsibility of exception handling


to the caller method. Then caller method is responsible to handle that
exception.

Ex-2

class Test3

public static void main(String[] args)throws InterruptedException{

Thread.sleep(5000);

Output:

Compile and running successfully

Ex:

import java.io.IOException;  

class Testthrows1{  

  void m()throws IOException{  

    throw new IOException("device error");//checked exception  

  }  

  void n()throws IOException{  

    m();  

  }  

  void p(){  

   try{  

techveerendras@gmail.com
Ph: 9014424466 Page 66
TechVeerendra’s
Software Solutions

    n();  

   }catch(Exception e){System.out.println("exception handled");}  

  }  

  public static void main(String args[]){  

   Testthrows1 obj=new Testthrows1();  

   obj.p();  

   System.out.println("normal flow...");  

  }  

}  

Output:

exception handled

normal flow...

Rule: If you are calling a method that declares an exception, you must either
caught or declare the exception.

There are two cases:

1. Case1:You caught the exception i.e. handle the exception using


try/catch.

2. Case2:You declare the exception i.e. specifying throws with the method.

Case1: You handle the exception

o In case you handle the exception, the code will be executed fine whether
exception occurs during the program or not.

Ex:

import java.io.*;  
techveerendras@gmail.com
Ph: 9014424466 Page 67
TechVeerendra’s
Software Solutions

class M{  

 void method()throws IOException{  

  throw new IOException("device error");  

 }  

}  

public class Testthrows2{  

   public static void main(String args[]){  

    try{  

     M m=new M();  

     m.method();  

    }catch(Exception e){System.out.println("exception handled");}     

  

    System.out.println("normal flow...");  

  }  

}  

Output:

exception handled

normal flow...

Case2: You declare the exception

o A)In case you declare the exception, if exception does not occur, the code
will be executed fine.

o B)In case you declare the exception if exception occures, an exception


will be thrown at runtime because throws does not handle the exception.

techveerendras@gmail.com
Ph: 9014424466 Page 68
TechVeerendra’s
Software Solutions

A) Program if exception does not occur

import java.io.*;  

class M{  

 void method()throws IOException{  

  System.out.println("device operation performed");  

 }  

}  

class Testthrows3{  

   public static void main(String args[])throws IOException{//declare excepti
on  

     M m=new M();  

     m.method();  

  

    System.out.println("normal flow...");  

  }  

}  

Output:device operation performed

normal flow...

B)Program if exception occurs

import java.io.*;  

class M{  

 void method()throws IOException{  

techveerendras@gmail.com
Ph: 9014424466 Page 69
TechVeerendra’s
Software Solutions

  throw new IOException("device error");  

 }  

}  

class Testthrows4{  

   public static void main(String args[])throws IOException{//declare excepti
on  

     M m=new M();  

     m.method();  

  

    System.out.println("normal flow...");  

  }  

}  

Output:Runtime Exception

Note :

 Hence the main objective of "throws" keyword is to delegate the


responsibility of exception handling to the caller method.
 "throws" keyword required only checked exceptions. Usage of throws for
unchecked exception there is no use.
 "throws" keyword required only to convince complier. Usage of throws
keyword doesn't prevent abnormal termination of the program.
 Hence recommended to use try-catch over throws keyword.

Example:

class Test

techveerendras@gmail.com
Ph: 9014424466 Page 70
TechVeerendra’s
Software Solutions

public static void main(String[] args)throws InterruptedException{

wish();

public static void wish()throws InterruptedException{

greet();

public static void greet()throws InterruptedException{

Thread.sleep(5000);

Output:

Compile and running successfully.

In the above program if we are removing at least one throws keyword then the
program won't compile.

Case 1:

We can use throws keyword only for Throwable types otherwise we will get
compile time error saying incompatible types.

class Test3{

public static void main(String[] args)

throws Test3

Output:

techveerendras@gmail.com
Ph: 9014424466 Page 71
TechVeerendra’s
Software Solutions

Compile time error

Test3.java:2: incompatible types

found : Test3

required: java.lang.Throwable

public static void main(String[] args) throws Test3

Ex-2:

class Test3 extends RuntimeException{

public static void main(String[] args) throws Test3

{}

Output:

Compile and running successfully.

Case 2:Example:

class Test3{

public static void main(String[] args){

throw new Exception();

Output:

Compile time error.

Test3.java:3: unreported exception java.lang.Exception; must be caught or


declared to be thrown

Ex:

class Test3{

techveerendras@gmail.com
Ph: 9014424466 Page 72
TechVeerendra’s
Software Solutions

public static void main(String[] args){

throw new Error();

Output:

Runtime error

Exception in thread "main" java.lang.Error

at Test3.main(Test3.java:3)

Case 3:

In our program within the try block, if there is no chance of rising an exception
then we can't wright catch block for that exception otherwise we will get
compile time error saying exception XXX is never thrown in body of
corresponding try statement. But this rule is applicable only for fully checked
exception.

Example:

techveerendras@gmail.com
Ph: 9014424466 Page 73
TechVeerendra’s
Software Solutions

Case 4:

We can use throws keyword only for constructors and methods but not for
classes.

Example:

Exception handling keywords summary:

1. try: To maintain risky code.

2. catch: To maintain handling code.

techveerendras@gmail.com
Ph: 9014424466 Page 74
TechVeerendra’s
Software Solutions

3. finally: To maintain cleanup code.

4. throw: To handover our created exception object to the JVM manually.

5. throws: To delegate responsibility of exception handling to the caller method.

Various possible compile time errors in exception handling:

1. Exception XXX has already been caught.

2. Unreported exception XXX must be caught or declared to be thrown.

3. Exception XXX is never thrown in body of corresponding try statement.

4. Try without catch or finally.

5. Catch without try.

6. Finally without try.

7. Incompatible types.

found:Test

requried:java.lang.Throwable;

8. Unreachable statement

Customized Exceptions (User defined Exceptions)

Sometimes we can create our own exception to meet our programming


requirements. Such types of exceptions are called customized exceptions (user
defined exceptions).

By the help of custom exception, you can have your own exception and
message.

Example:
techveerendras@gmail.com
Ph: 9014424466 Page 75
TechVeerendra’s
Software Solutions

1. InSufficientFundsException

2. TooYoungException

3. TooOldException

Ex: InvalidAgeException.java

class InvalidAgeException extends Exception{  

 InvalidAgeException(String s){  

  super(s);  

 }  

}  

TestCustomException1.java

class TestCustomException1{  

   static void validate(int age)throws InvalidAgeException{  

     if(age<18)  

      throw new InvalidAgeException("not valid");  

     else  

      System.out.println("welcome to vote");  

   }     

   public static void main(String args[]){  

      try{  

      validate(13);  

      }

catch(Exception m){

techveerendras@gmail.com
Ph: 9014424466 Page 76
TechVeerendra’s
Software Solutions

System.out.println("Exception occured: "+m);

}  

      System.out.println("rest of the code...");  

  }  

}  

Output:

Exception occured: InvalidAgeException:not valid

rest of the code...

Program:

class TooYoungException extends RuntimeException

TooYoungException(String s)

super(s);

class TooOldException extends RuntimeException

TooOldException(String s)

super(s);

techveerendras@gmail.com
Ph: 9014424466 Page 77
TechVeerendra’s
Software Solutions

class CustomizedExceptionDemo

public static void main(String[] args){

int age=Integer.parseInt(args[0]);

if(age<25)

throw new TooYoungException("please wait some more time.... u will get


best match");

else if(age>50)

throw new TooOldException("u r age already crossed....no chance of getting


married");

else

System.out.println("you will get match details soon by e-mail");

}}}

Output:

1. E:\scjp>java CustomizedExceptionDemo 61

Exception in thread "main" TooYoungException:

please wait some more time.... u will get best match

techveerendras@gmail.com
Ph: 9014424466 Page 78
TechVeerendra’s
Software Solutions

at CustomizedExceptionDemo.main(CustomizedExceptionDemo.java:21)

2. E:\scjp>java CustomizedExceptionDemo 27

You will get match details soon by e-mail

3. E:\scjp>java CustomizedExceptionDemo 9

Exception in thread "main" TooOldException:

u r age already crossed....no chance of getting married

at CustomizedExceptionDemo.main(CustomizedExceptionDemo.java:25)

Note: It is highly recommended to maintain our customized exceptions as


unchecked by extending RuntimeException.

We can catch any Throwable type including Errors also.

techveerendras@gmail.com
Ph: 9014424466 Page 79
TechVeerendra’s
Software Solutions

Top-10 Exceptions:

Based on the person who is raising exception, all exceptions are divided into
two types.

They are:

1) JVM Exceptions:

2) Programmatic exceptions:

JVM Exceptions:

The exceptions which are raised automatically by the jvm whenever a


particular event occurs, are called JVM Exceptions.

Example:

1) ArrayIndexOutOfBoundsException(AIOOBE)

2) NullPointerException (NPE).

Programmatic Exceptions:

The exceptions which are raised explicitly by the programmer (or) by the API
developer are called programmatic exceptions.

Example:

1) IllegalArgumentException(IAE).

techveerendras@gmail.com
Ph: 9014424466 Page 80
TechVeerendra’s
Software Solutions

Top 10 Exceptions:

1. ArrayIndexOutOfBoundsException:

It is the child class of RuntimeException and hence it is unchecked. Raised


automatically by the JVM whenever we are trying to access array element with
out of range index.

Example:

class Test{

public static void main(String[] args){

int[] x=new int[10];

System.out.println(x[0]);//valid

System.out.println(x[100]);//AIOOBE

System.out.println(x[-100]);//AIOOBE

2. NullPointerException:

It is the child class of RuntimeException and hence it is unchecked. Raised


automatically by the JVM, whenever we are trying to call any method on null.

Example:

class Test{

public static void main(String[] args){

String s=null;

System.out.println(s.length()); //R.E: NullPointerException

techveerendras@gmail.com
Ph: 9014424466 Page 81
TechVeerendra’s
Software Solutions

3. StackOverFlowError:

It is the child class of Error and hence it is unchecked. Whenever we are trying
to invoke recursive method call JVM will raise StackOverFloeError
automatically.

Example:

class Test

public static void methodOne()

methodTwo();

public static void methodTwo()

methodOne();

public static void main(String[] args)

methodOne();

Output:

Run time error: StackOverFloeError

techveerendras@gmail.com
Ph: 9014424466 Page 82
TechVeerendra’s
Software Solutions

4. NoClassDefFoundError:

It is the child class of Error and hence it is unchecked. JVM will raise this error
automatically whenever it is unable to find required .class file.

Example: java

Test If Test.class is not available. Then we will get NoClassDefFound error.

5. ClassCastException:

It is the child class of RuntimeException and hence it is unchecked. Raised


automatically by the JVM whenever we are trying to type cast parent object to
child type.

6. ExceptionInInitializerError:

It is the child class of Error and it is unchecked. Raised automatically by the


JVM, if any exception occurs while performing static variable initialization and
static block execution.

Example 1:

class Test{

static int i=10/0;

Output:

Runtime exception:

Exception in thread "main" java.lang.ExceptionInInitializerError

techveerendras@gmail.com
Ph: 9014424466 Page 83
TechVeerendra’s
Software Solutions

Example 2:

class Test{

static {

String s=null;

System.out.println(s.length());

}}

Output:

Runtime exception:

Exception in thread "main" java.lang.ExceptionInInitializerError

7. IllegalArgumentException:

It is the child class of RuntimeException and hence it is unchecked. Raised


explicitly by the programmer (or) by the API developer to indicate that a method
has been invoked with inappropriate argument.

Example:

class Test{

public static void main(String[] args){

Thread t=new Thread();

t.setPriority(10);//valid

t.setPriority(100);//invalid---Thread priority in b/w 1to 10 only

}}

Output:

Runtime exception

Exception in thread "main" java.lang.IllegalArgumentException.

techveerendras@gmail.com
Ph: 9014424466 Page 84
TechVeerendra’s
Software Solutions

8. NumberFormatException:

It is the child class of IllegalArgumentException and hence is unchecked.


Raised explicitly by the programmer or by the API developer to indicate that we
are attempting to convert string to the number. But the string is not properly
formatted.

Example:

class Test{

public static void main(String[] args){

int i=Integer.parseInt("10");

int j=Integer.parseInt("ten");

}}

Output:

Runtime Exception

Exception in thread "main" java.lang.NumberFormatException: For input


string: "ten"

9. IllegalStateException:

It is the child class of RuntimeException and hence it is unchecked. Raised


explicitly by the programmer or by the API developer to indicate that a method
has been invoked at inappropriate time.

Ex:

techveerendras@gmail.com
Ph: 9014424466 Page 85
TechVeerendra’s
Software Solutions

HttpSession session=req.getSession();

System.out.println(session.getId());

session.invalidate();

System.out.println(session.getId()); // illgalstateException

10. AssertionError:

It is the child class of Error and hence it is unchecked. Raised explicitly by the
programmer or by API developer to indicate that Assert statement fails.

Example:

assert(false);

Exception/Error Raised by
1. AIOOBE Raised automatically by JVM(JVM
2. NPE(NullPointerException) Exceptions)
3. StackOverFlowError
4. NoClassDefFoundError
5. CCE(ClassCastException)
6. ExceptionInInitializerError

1. IAE(IllegalArgumentException)
2. NFE(NumberFormatException) Raised explicitly either by programmer or
3. ISE(IllegalStateException) by API developer (Programatic Exceptions).
4. AE(AssertionError)

techveerendras@gmail.com
Ph: 9014424466 Page 86
TechVeerendra’s
Software Solutions

1.7 Version Enhancements:

As part of 1.7 version enhancements in Exception Handling the following 2


concepts introduced.

1. try with resources

2. multi catch block

1. try with resources:

Untill 1.6 version it is highly recommended to write finally block to close all
resources which are open as part of try block.

Ex:

Class Test{

public static void main(String args[]){

BufferedReader br=null;

try{

br=new BufferedReader(new FileReader("abc.txt"));

//use br based on our requirements

catch(IOException e) {

// handling code

finally {
techveerendras@gmail.com
Ph: 9014424466 Page 87
TechVeerendra’s
Software Solutions

if(br != null)

br.close();

Problems in this approach:

 Compulsory programmer is required to close all opened resources with


increases the complexity of the programming.
 Compulsory we should write finally block explicitly which increases
length of the code and reviews readability.
 To overcome these problems Sun People introduced "try with resources"
in 1.7 version.

Adv of 1.7:

The main advantage of "try with resources" is the resources which are opened
as part of try block will be closed automatically

Once the control reaches end of the try block either normally or abnormally
and hence we are not required to close explicitly so that the complexity of
programming will be reduced. It is not required to write finally block explicitly
and hence length of the code will be reduced and readability will be improved.

Ex:

try(BufferedReader br=new BufferedReader(new FileReader("abc.txt")))

use be based on our requirement, br will be closed automatically ,

Onec control reaches end of try either normally or abnormally and we are not
required to close explicitly

catch(IOException e) {
techveerendras@gmail.com
Ph: 9014424466 Page 88
TechVeerendra’s
Software Solutions

// handling code

Try-with-resources Example 1;

import java.io.FileOutputStream;    

public class TryWithResources {    

public static void main(String args[]){      

        // Using try-with-resources  

try(FileOutputStream fos =newFileOutputStream
“F:/WorkSpace/VeeruClasses/Java6PM/EH/abc.txt")){      

String msg = "Welcome to java !";      

byte byteArray[] = msg.getBytes(); //converting string into byte array      

fos.write(byteArray);  

System.out.println("Message written to file successfuly!");      

}catch(Exception exception){  

       System.out.println(exception);  

}      

}      

}    

Output:

Message written to file successfuly!

Output of file

Welcome to java!

techveerendras@gmail.com
Ph: 9014424466 Page 89
TechVeerendra’s
Software Solutions

Try-with-resources Example: Using Multiple Resources:

import java.io.DataInputStream;  

import java.io.FileInputStream;  

import java.io.FileOutputStream;  

import java.io.InputStream;    

public class TryWithResources {    

public static void main(String args[]){      

        // Using try-with-resources  

try(    // Using multiple resources  

        FileOutputStream fos =new FileOutputStream(“F:/WorkSpace/VeeruC
lasses/Java6PM/EH/abc.txt");  

        InputStream input = new FileInputStream(“F:/WorkSpace/VeeruClass
es/Java6PM/EH/abc.txt")){  

        // -----------------------------Code to write data into file---------------------
-----------------------//  

        String msg = "Welcome to java !";      

        byte byteArray[] = msg.getBytes();  // Converting string into byte array 
     

        fos.write(byteArray);  // Writing  data into file  

        System.out.println("------------Data written into file--------------");  

        System.out.println(msg);  

        // -----------------------------Code to read data from file---------------------
------------------------//  

techveerendras@gmail.com
Ph: 9014424466 Page 90
TechVeerendra’s
Software Solutions

        // Creating input stream instance  

        DataInputStream inst = new DataInputStream(input);    

        int data = input.available();    

        // Returns an estimate of the number of bytes that can be read from 

this input stream.   

        byte[] byteArray2 = new byte[data]; //    

        inst.read(byteArray2);    

        String str = new String(byteArray2); // passing byte array into String 
constructor  

        System.out.println("------------Data read from file--------------");  

        System.out.println(str); // display file data  

}catch(Exception exception){  

       System.out.println(exception);  

}     

}      

}  

Output:

------------Data written into file--------------

Welcome to java!

------------Data read from file--------------

Welcome to java!

You can use catch and finally blocks with try-with-resources statement just
like an ordinary try statement.

techveerendras@gmail.com
Ph: 9014424466 Page 91
TechVeerendra’s
Software Solutions

Note - In a try-with-resources statement, catch or finally block executes


after closing of the declared resources.

Try-with-resources Example: using finally block

import java.io.FileOutputStream;    

public class TryWithResources {    

public static void main(String args[]){      

try(    FileOutputStream fileOutputStream=  

  new FileOutputStream(“F:/WorkSpace/VeeruClasses/Java6PM/EH/abc.tx
t")){  

    // -----------------------------Code to write data into file------------------------
--------------------//  

        String msg = "Welcome to java !";      

        byte byteArray[] = msg.getBytes();  // Converting string into byte array 
     

        fileOutputStream.write(byteArray);  // Writing  data into file  

        System.out.println("Data written successfully!");  

}catch(Exception exception){  

       System.out.println(exception);  

}  

finally{  

       System.out.println("Finally executes after closing of declared resources
.");  

}  

}      

techveerendras@gmail.com
Ph: 9014424466 Page 92
TechVeerendra’s
Software Solutions

}  

Output:

Data written successfully!

Finally executes after closing of declared resources.

Conclusions:

1. We can declare any no of resources but all these resources should be


seperated with ;(semicolon)

try(R1 ; R2 ; R3)

-------------

-------------

2. All resources should be AutoCloseable resources. A resource is said to be


auto closable if and only if the corresponding class implements the
java.lang.AutoCloseable interface either directly or indirectly.

All database related, network related and file io related resources already
implemented AutoCloseable interface. Being a programmer we should aware
and we are not required to do anything extra.

3. All resource reference variables are implicitly final and hence we can't
perform reassignment within the try block.

try(BufferedReader br=new BufferedReader(new FileReader("abc.txt"))) ;

br=new BufferedReader(new FileReader("abc.txt"));

techveerendras@gmail.com
Ph: 9014424466 Page 93
TechVeerendra’s
Software Solutions

output :

CE : Can't reassign a value to final variable br

4. Untill 1.6 version try should be followed by either catch or finally but 1.7
version we can take only try with resource without catch or finally

try(R)

{ //valid

5. The main advantage of "try with resources" is finally block will become
dummy

because we are not required to close resources of explicitly.

Multi catch block:


Until 1.6 version ,Eventhough Multiple Exceptions having same handling code
we have to write a separate catch block for every exceptions, it increases length
of the code and reviews readability

try{

-----------------

-----------------

catch(ArithmeticException e) {

e.printStackTrace();

catch(NullPointerException e) {

e.printStackTrace();

techveerendras@gmail.com
Ph: 9014424466 Page 94
TechVeerendra’s
Software Solutions

catch(ClassCastException e) {

System.out.println(e.getMessage());

catch(IOException e) {

System.out.println(e.getMessage());

To overcome this problem Sun People introduced "Multi catch block" concept in
1.7 version.

The main advantage of multi catch block is we can write a single catch block ,
which can handle multiple different exceptions

try{

-----------------

-----------------

catch(ArithmeticException | NullPointerException e) {

e.printStackTrace();

catch(ClassCastException | IOException e) {

System.out.println(e.getMessage());

In multi catch block, there should not be any relation between Exception
types(either child to parent Or parent to child Or same type , otherwise we will
get Compile time error ).

techveerendras@gmail.com
Ph: 9014424466 Page 95
TechVeerendra’s
Software Solutions

Ex:

Catching Multiple Exception Types (with java 1.6)Example 1

public class MultipleExceptionExample{    

    public static void main(String args[]){    

        try{    

            int array[] = newint[10];    

            array[10] = 30/0;    

        }    

        catch(ArithmeticException e){  

            System.out.println(e.getMessage());  

        }    

        catch(ArrayIndexOutOfBoundsException e){  

            System.out.println(e.getMessage());  

        }    

        catch(Exception e){  

            System.out.println(e.getMessage());  

techveerendras@gmail.com
Ph: 9014424466 Page 96
TechVeerendra’s
Software Solutions

        }    

     }    

}  

Output:

/ by zero

Catching Multiple Exception Types Example 2

What Java 7 provides us:

public class MultipleExceptionExample{    

    public static void main(String args[]){    

        try{    

            int array[] = newint[10];    

            array[10] = 30/0;    

        }    

        catch(ArithmeticException | ArrayIndexOutOfBoundsException e){  

            System.out.println(e.getMessage());  

        }    

     }    

}  

Output:

/ by zero

Catching Multiple Exception Types Example 3

public class MultipleExceptionExample{    

    public static void main(String args[]){    

techveerendras@gmail.com
Ph: 9014424466 Page 97
TechVeerendra’s
Software Solutions

        try{    

            int array[] = newint[10];    

            array[10] = 30/0;    

        }    

        catch(Exception | ArithmeticException | ArrayIndexOutOfBoundsExc
eption e){  

            System.out.println(e.getMessage());  

        }    

     }    

}  

Output:

Compile-time error: The exception ArithmeticException is already caught by


the alternative Exception

So here, in case when your are catching multiple exceptions, follow the rule of
generalized to more specialized. It means that, if you are using super (general)
class, don't use child (specialized) class.

Note - Catch block which handles more than one exception type makes the
catch parameter implicitly final. In the above example, the catch parameter "e"
is final and therefore you cannot assign any value to it.

Exception Propagation:

Within a method if an exception raised and if that method doesn't handle that
exception, then Exception object will be propagated to the caller then caller
method is responsible to handle that exceptions. This process is called
Exception Propagation.

An exception is first thrown from the top of the stack and if it is not caught, it
techveerendras@gmail.com
Ph: 9014424466 Page 98
TechVeerendra’s
Software Solutions

drops down the call stack to the previous method,If not caught there, the
exception again drops down to the previous method, and so on until they are
caught or until they reach the very bottom of the call stack.This is called
exception propagation.

Rule: By default Unchecked Exceptions are forwarded in calling chain


(propagated).

Program of Exception Propagation

class TestExceptionPropagation1{  

  void m(){  

    int data=50/0;  

  }  

  void n(){  

    m();  

  }  

  void p(){  

   try{  

    n();  

   }catch(Exception e){System.out.println("exception handled");}  

  }  

  public static void main(String args[]){  

   TestExceptionPropagation1 obj=new TestExceptionPropagation1();  

   obj.p();  

   System.out.println("normal flow...");  

  }  

techveerendras@gmail.com
Ph: 9014424466 Page 99
TechVeerendra’s
Software Solutions

}  

Output:

exception handled

normal flow...

In the above example exception occurs in m() method where it is not


handled,so it is propagated to previous n() method where it is not handled,
again it is propagated to p() method where exception is handled.

Exception can be handled in any method in call stack either in main()


method,p() method,n() method or m() method.

Rule: By default, Checked Exceptions are not forwarded in calling chain


(propagated).

Program which describes that checked exceptions are not propagated

class TestExceptionPropagation2{  

  void m(){  

    throw new java.io.IOException("device error");//checked exception  

  }  

  void n(){  

techveerendras@gmail.com
Ph: 9014424466 Page 100
TechVeerendra’s
Software Solutions

    m();  

  }  

  void p(){  

   try{  

    n();  

   }catch(Exception e){System.out.println("exception handeled");}  

  }  

  public static void main(String args[]){  

   TestExceptionPropagation2 obj=new TestExceptionPropagation2();  

   obj.p();  

   System.out.println("normal flow");  

  }  

}  

Output:Compile Time Error

Rethrowing an Exception:

To convert the one exception type to another exception type , we can use
rethrowing exception concept.

class Test

public static void main(String[] args){

try {

System.out.println(10/0);

techveerendras@gmail.com
Ph: 9014424466 Page 101
TechVeerendra’s
Software Solutions

catch(ArithmeticException e) {

throw new NullPointerException();

Output:

RE: NPE

ExceptionHandling with MethodOverriding in Java

There are many rules if we talk about methodoverriding with exception


handling. The Rules are as follows:

If the superclass method does not declare an exception

 If the superclass method does not declare an exception, subclass


overridden method cannot declare the checked exception but it can
declare unchecked exception.

If the superclass method declares an exception

 If the superclass method declares an exception, subclass overridden


method can declare same, subclass exception or no exception but cannot
declare parent exception.

1. If the superclass method does not declare an exception

techveerendras@gmail.com
Ph: 9014424466 Page 102
TechVeerendra’s
Software Solutions

1) Rule: If the superclass method does not declare an exception, subclass


overridden method cannot declare the checked exception.

import java.io.*;  

class Parent{  

  void msg(){

System.out.println("parent");

}  

}  

class TestExceptionChild extends Parent{  

  void msg()throws IOException{  

    System.out.println("TestExceptionChild");  

  }  

  public static void main(String args[]){  

   Parent p=new TestExceptionChild();  

   p.msg();  

  }  

}  

Output:Compile Time Error

2) Rule: If the superclass method does not declare an exception, subclass


overridden method cannot declare the checked exception but can declare
unchecked exception.

import java.io.*;  

class Parent{  

techveerendras@gmail.com
Ph: 9014424466 Page 103
TechVeerendra’s
Software Solutions

  void msg(){

System.out.println("parent");

}  

}  

class TestExceptionChild1 extends Parent{  

  void msg()throws ArithmeticException{  

    System.out.println("child");  

  }  

  public static void main(String args[]){  

   Parent p=new TestExceptionChild1();  

   p.msg();  

  }  

}  

Output:child

If the superclass method declares an exception:

1) Rule: If the superclass method declares an exception, subclass overridden


method can declare same, subclass exception or no exception but cannot
declare parent exception.

Example in case subclass overridden method declares parent exception

import java.io.*;  

class Parent{  

  void msg()throws ArithmeticException{

techveerendras@gmail.com
Ph: 9014424466 Page 104
TechVeerendra’s
Software Solutions

System.out.println("parent");

}  

}  

class TestExceptionChild2 extends Parent{  

  void msg()throws Exception{

System.out.println("child");

}  

  public static void main(String args[]){  

   Parent p=new TestExceptionChild2();  

   try{  

   p.msg();  

   }catch(Exception e){}  

  }  

}  

Output:Compile Time Error

Example in case subclass overridden method declares same exception

import java.io.*;  

class Parent{  

  void msg()throws Exception{

System.out.println("parent");

}  

}  

techveerendras@gmail.com
Ph: 9014424466 Page 105
TechVeerendra’s
Software Solutions

  

class TestExceptionChild3 extends Parent{  

  void msg()throws Exception{

System.out.println("child");

}  

  public static void main(String args[]){  

   Parent p=new TestExceptionChild3();  

   try{  

   p.msg();  

   }catch(Exception e){}  

  }  

}  

Output:child

Example in case subclass overridden method declares subclass


exception

import java.io.*;  

class Parent{  

  void msg()throws Exception{

System.out.println("parent");

}  

}  

class TestExceptionChild4 extends Parent{  

  void msg()throws ArithmeticException{

techveerendras@gmail.com
Ph: 9014424466 Page 106
TechVeerendra’s
Software Solutions

System.out.println("child");

}  

  public static void main(String args[]){  

   Parent p=new TestExceptionChild4();  

   try{  

   p.msg();  

   }catch(Exception e){}  

  }  

}  

Output:child

Example in case subclass overridden method declares no exception

import java.io.*;  

class Parent{  

  void msg()throws Exception{

System.out.println("parent");

}  

}  

class TestExceptionChild5 extends Parent{  

  void msg(){System.out.println("child");}  

  public static void main(String args[]){  

   Parent p=new TestExceptionChild5();  

   try{  

   p.msg();  

techveerendras@gmail.com
Ph: 9014424466 Page 107
TechVeerendra’s
Software Solutions

   }catch(Exception e){}  

  }  

}  

Output:child

Difference between throw and throws in Java

There are many differences between throw and throws keywords. A list of
differences between throw and throws are given below:

No throw throws
.

1) Java throw keyword is used to Java throws keyword is used to


explicitly throw an exception. declare an exception.

2) Checked exception cannot be Checked exception can be propagated


propagated using throw only. with throws.

3) Throw is followed by an Throws is followed by class.


instance.

4) Throw is used within the Throws is used with the method


method. signature.

5) You cannot throw multiple You can declare multiple exceptions


exceptions. e.g.
public void method()throws
IOException,SQLException.

Java throw example

void m(){  

techveerendras@gmail.com
Ph: 9014424466 Page 108
TechVeerendra’s
Software Solutions

throw new ArithmeticException("sorry");  

}  

Java throws example

void m()throws ArithmeticException{  

//method code  

}  

Java throw and throws example

void m()throws ArithmeticException{  

throw new ArithmeticException("sorry");  

}  

techveerendras@gmail.com
Ph: 9014424466 Page 109
TechVeerendra’s
Software Solutions

techveerendras@gmail.com
Ph: 9014424466 Page 110

You might also like