Exception Handling in Java
Exception Handling in Java
Software Solutions
Example:
SleepingException
TyrePunchuredException
FileNotFoundException ...etc
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
catch(FileNotFoundException e)
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
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
Wish();
greet();
System.out.println("Hello");
techveerendras@gmail.com
Ph: 9014424466 Page 3
TechVeerendra’s
Software Solutions
Output:
Hello
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.
Example:
class Test
wish();
greet();
System.out.println(10/0);
techveerendras@gmail.com
Ph: 9014424466 Page 5
TechVeerendra’s
Software Solutions
Output:
atTest.greet(Test.java:10)
atTest.wish(Test.java:7)
atTest.main(Test.java:4)
Daigram:
Example:
class Test
wish();
techveerendras@gmail.com
Ph: 9014424466 Page 6
TechVeerendra’s
Software Solutions
greet();
System.out.println(10/0);
System.out.println(“good morning”);
Example:
class Test
wish();
System.out.println(10/0);
techveerendras@gmail.com
Ph: 9014424466 Page 7
TechVeerendra’s
Software Solutions
System.out.println(“Hi”);
System.out.println(“good morning”);
Note: In our program, if at least one method terminated abnormally the then
that program termination is abnormal termination.
techveerendras@gmail.com
Ph: 9014424466 Page 8
TechVeerendra’s
Software Solutions
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.
techveerendras@gmail.com
Ph: 9014424466 Page 9
TechVeerendra’s
Software Solutions
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
1. HallTicketMissingException
2. PenNotWorkingException
3. FileNotFoundException
Ex:
Import java.lang.*;
class Test
Pw.println(“hello”);
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.
1) Checked Exception
2) Unchecked Exception
3) Error
techveerendras@gmail.com
Ph: 9014424466 Page 12
TechVeerendra’s
Software Solutions
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
Example:
Exception
1. Throwable.
2. Exception.
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
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.
techveerendras@gmail.com
Ph: 9014424466 Page 14
TechVeerendra’s
Software Solutions
Example:
try
Risky code
catch(Exception e)
Handling code
class Test
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.
class Test{
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:
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
try{
//code that may throw exception
catch(Exception_class_Name ref){
}
try{
//code that may throw exception
finally{
}
Java catch block is used to handle the Exception. It must be used after the try
block only.
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:
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:
techveerendras@gmail.com
Ph: 9014424466 Page 19
TechVeerendra’s
Software Solutions
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:
techveerendras@gmail.com
Ph: 9014424466 Page 20
TechVeerendra’s
Software Solutions
try{
statement-1;
statement-2;
statement-3;
catch(X e) {
statement-4;
statement5;
1, 2, 3, 5 normal termination.
try{
System.out.println("s1...");
System.out.println("s2");
System.out.println("s3");
//int data=100/0;
techveerendras@gmail.com
Ph: 9014424466 Page 21
TechVeerendra’s
Software Solutions
catch(ArithmeticException e){
System.out.println("s4");
System.out.println("s5");
1, 4, 5 normal termination.
try{
System.out.println("s1...");
System.out.println(10/0);
System.out.println("s3");
techveerendras@gmail.com
Ph: 9014424466 Page 22
TechVeerendra’s
Software Solutions
//int data=100/0;
catch(ArithmeticException e){
System.out.println(e);
System.out.println("s5");
try{
System.out.println("s1...");
System.out.println(10/0);
System.out.println("s3");
techveerendras@gmail.com
Ph: 9014424466 Page 23
TechVeerendra’s
Software Solutions
//int data=100/0;
catch(NullPointerException e){
System.out.println(e);
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.
try{
System.out.println("s1...");
System.out.println(10/0);
System.out.println("s3");
//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);
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.
printStackTrace():
techveerendras@gmail.com
Ph: 9014424466 Page 25
TechVeerendra’s
Software Solutions
Stack trace
Description
Example:
techveerendras@gmail.com
Ph: 9014424466 Page 26
TechVeerendra’s
Software Solutions
Example:
try
catch(Exception e)
default handler
Ex:
try{
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.
try
catch(FileNotFoundException e)
catch(ArithmeticException e)
catch(SQLException e)
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
class Test
try
System.out.println(10/0);
catch(Exception e)
e.printStackTrace();
catch(ArithmeticException e)
e.printStackTrace();
}}}
CE: Exception
techveerendras@gmail.com
Ph: 9014424466 Page 30
TechVeerendra’s
Software Solutions
class Test
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)
techveerendras@gmail.com
Ph: 9014424466 Page 33
TechVeerendra’s
Software Solutions
Example:
try
risky code
catch(x e)
handling code
finally
techveerendras@gmail.com
Ph: 9014424466 Page 34
TechVeerendra’s
Software Solutions
cleanup code
Note: If you don't handle exception, before terminating the program, JVM
executes finally block (if any).
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.
class Test
try
catch(ArithmeticException e)
finally
Output:
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
class Test
try
techveerendras@gmail.com
Ph: 9014424466 Page 37
TechVeerendra’s
Software Solutions
System.out.println(10/0);
catch(ArithmeticException e)
finally
Output:
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:
class Test
try
System.out.println(10/0);
catch(NullPointerException e)
techveerendras@gmail.com
Ph: 9014424466 Page 39
TechVeerendra’s
Software Solutions
finally
Output:
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
}
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
try
return;
catch(ArithmeticException e)
finally
techveerendras@gmail.com
Ph: 9014424466 Page 41
TechVeerendra’s
Software Solutions
}}
Output:
Note: If return statement present try, catch and finally blocks then finally
block return statement will be considered.
Example:
class Test
System.out.println(m1());
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.
Example:
class Test
try
System.out.println("try");
System.exit(0);
catch(ArithmeticException e)
techveerendras@gmail.com
Ph: 9014424466 Page 43
TechVeerendra’s
Software Solutions
finally
}}
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.
final:
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:
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.
class FinalExample{
public static void main(String[] args){
final int x=100;
x=200;//Compile Time Error
}}
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");}
}}
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();
}}
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;
The try block within a try block is known as nested try block in java.
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..");
}
}
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 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.
techveerendras@gmail.com
Ph: 9014424466 Page 51
TechVeerendra’s
Software Solutions
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
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.
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
techveerendras@gmail.com
Ph: 9014424466 Page 57
TechVeerendra’s
Software Solutions
throw exception;
throw new IOException("sorry device error);
class Test
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.
class Test
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:
techveerendras@gmail.com
Ph: 9014424466 Page 59
TechVeerendra’s
Software Solutions
Ex:
class Test3
throw e;
Output:
Ex:
class Test3
throw e;
Output:
techveerendras@gmail.com
Ph: 9014424466 Page 60
TechVeerendra’s
Software Solutions
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
System.out.println(10/0);
System.out.println("hello");
Output:
at Test3.main(Test3.java:4)
Ex:
class Test3
System.out.println("hello");
techveerendras@gmail.com
Ph: 9014424466 Page 61
TechVeerendra’s
Software Solutions
Output:
Case 3:
We can use throw keyword only for Throwable types otherwise we will get
compile time error saying incomputable types.
Ex:
class Test3
Output:
found : Test3
required: java.lang.Throwable
Ex:
techveerendras@gmail.com
Ph: 9014424466 Page 62
TechVeerendra’s
Software Solutions
Output:
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
out.println("hello");
CE :
techveerendras@gmail.com
Ph: 9014424466 Page 63
TechVeerendra’s
Software Solutions
Example:
class Test3
Thread.sleep(5000);
return_type method_name() throws exception_class_name{
//method code
}
techveerendras@gmail.com
Ph: 9014424466 Page 64
TechVeerendra’s
Software Solutions
We can handle this compile time error by using the following 2 ways.
class Test3
main(String[] args){
try{
Thread.sleep(5000);
catch(InterruptedException e){
Output:
Successfully
techveerendras@gmail.com
Ph: 9014424466 Page 65
TechVeerendra’s
Software Solutions
Ex-2
class Test3
Thread.sleep(5000);
Output:
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.
2. Case2:You declare the exception i.e. specifying throws with the method.
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...
o A)In case you declare the exception, if exception does not occur, the code
will be executed fine.
techveerendras@gmail.com
Ph: 9014424466 Page 68
TechVeerendra’s
Software Solutions
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...");
}
}
normal flow...
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 :
Example:
class Test
techveerendras@gmail.com
Ph: 9014424466 Page 70
TechVeerendra’s
Software Solutions
wish();
greet();
Thread.sleep(5000);
Output:
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{
throws Test3
Output:
techveerendras@gmail.com
Ph: 9014424466 Page 71
TechVeerendra’s
Software Solutions
found : Test3
required: java.lang.Throwable
Ex-2:
{}
Output:
Case 2:Example:
class Test3{
Output:
Ex:
class Test3{
techveerendras@gmail.com
Ph: 9014424466 Page 72
TechVeerendra’s
Software Solutions
Output:
Runtime 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:
techveerendras@gmail.com
Ph: 9014424466 Page 74
TechVeerendra’s
Software Solutions
7. Incompatible types.
found:Test
requried:java.lang.Throwable;
8. Unreachable statement
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:
Program:
TooYoungException(String s)
super(s);
TooOldException(String s)
super(s);
techveerendras@gmail.com
Ph: 9014424466 Page 77
TechVeerendra’s
Software Solutions
class CustomizedExceptionDemo
int age=Integer.parseInt(args[0]);
if(age<25)
else if(age>50)
else
}}}
Output:
1. E:\scjp>java CustomizedExceptionDemo 61
techveerendras@gmail.com
Ph: 9014424466 Page 78
TechVeerendra’s
Software Solutions
at CustomizedExceptionDemo.main(CustomizedExceptionDemo.java:21)
2. E:\scjp>java CustomizedExceptionDemo 27
3. E:\scjp>java CustomizedExceptionDemo 9
at CustomizedExceptionDemo.main(CustomizedExceptionDemo.java:25)
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:
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:
Example:
class Test{
System.out.println(x[0]);//valid
System.out.println(x[100]);//AIOOBE
System.out.println(x[-100]);//AIOOBE
2. NullPointerException:
Example:
class Test{
String s=null;
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
methodTwo();
methodOne();
methodOne();
Output:
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
5. ClassCastException:
6. ExceptionInInitializerError:
Example 1:
class Test{
Output:
Runtime exception:
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:
7. IllegalArgumentException:
Example:
class Test{
t.setPriority(10);//valid
}}
Output:
Runtime exception
techveerendras@gmail.com
Ph: 9014424466 Page 84
TechVeerendra’s
Software Solutions
8. NumberFormatException:
Example:
class Test{
int i=Integer.parseInt("10");
int j=Integer.parseInt("ten");
}}
Output:
Runtime Exception
9. IllegalStateException:
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
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{
BufferedReader br=null;
try{
catch(IOException e) {
// handling code
finally {
techveerendras@gmail.com
Ph: 9014424466 Page 87
TechVeerendra’s
Software Solutions
if(br != null)
br.close();
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:
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:
Output of file
Welcome to java!
techveerendras@gmail.com
Ph: 9014424466 Page 89
TechVeerendra’s
Software Solutions
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:
Welcome to java!
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
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:
Conclusions:
try(R1 ; R2 ; R3)
-------------
-------------
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.
techveerendras@gmail.com
Ph: 9014424466 Page 93
TechVeerendra’s
Software Solutions
output :
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
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:
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
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
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:
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.
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...
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");
}
}
Rethrowing an Exception:
To convert the one exception type to another exception type , we can use
rethrowing exception concept.
class Test
try {
System.out.println(10/0);
techveerendras@gmail.com
Ph: 9014424466 Page 101
TechVeerendra’s
Software Solutions
catch(ArithmeticException e) {
Output:
RE: NPE
techveerendras@gmail.com
Ph: 9014424466 Page 102
TechVeerendra’s
Software Solutions
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();
}
}
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
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){}
}
}
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
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
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
There are many differences between throw and throws keywords. A list of
differences between throw and throws are given below:
No throw throws
.
void m(){
techveerendras@gmail.com
Ph: 9014424466 Page 108
TechVeerendra’s
Software Solutions
throw new ArithmeticException("sorry");
}
void m()throws ArithmeticException{
//method code
}
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