Exception Handling
Exception Handling
Exception Handling
Example:
SleepingException
TyrePunchuredException
FileNotFoundException ...etc.
The Exception Handling in Java is one of the powerful mechanism to handle the
runtime errors so that normal flow of the application can be maintained.
In Java, an exception is an event that disrupts the normal flow of the program. It is
an object which is thrown at runtime.
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.
Ex:-
statement 1;
statement 2;
statement 3;
statement 4;
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;
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.
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. A hierarchy of Java Exception
classes are given below:
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");
Output:
Hello
Default Exception Handling in Java:
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.
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{
public static void main(String[] args){
wish();
}
public static void wish(){
greet();
}
public static void greet(){
System.out.println(10/0);
}
}
Output:
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();
}
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);
}
If all methods terminated normally then only the program termination is normal
termination.
The java.lang.Throwable class is the root class of Java Exception hierarchy which
is inherited by two subclasses: Exception and Error.
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.
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
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
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.
Unchecked exceptions: The exceptions which are not checked by the compiler
whether programmer handing or not, are called unchecked exceptions.
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
The classes which directly inherit Throwable class except RuntimeException and
Error are known as checked exceptions
2) Unchecked Exception
3) Error
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
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
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.
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
}
Java try block:-
Java try block is used to enclose the code that might throw an exception. It must be
used within the method.
If an exception occurs at the particular statement of try block, the rest of the block
code will not execute. So, it is recommended not to keeping the code in try block
that will not throw an exception.
try{
//code that may throw an exception
}
finally{
}
Java catch block
Java catch block is used to handle the Exception by declaring the type of exception
within the parameter. The declared exception must be the parent class exception
( i.e., Exception) or the generated exception type. However, the good approach is
to declare the generated type of exception.
The catch block must be used after the try block only. You can use multiple catch
block with a single try block.
Output:
statement1
RE:AE:/by zero
at Test.main()
Abnormal termination.
There can be 100 lines of code after exception. So all the code after exception will
not be executed.
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
5
statement3
Normal termination.
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, 10/0 raises an ArithmeticException which is handled by a
try-catch block.
Note: If we kept the code in a try block that will not throw an exception.
public class Example3 {
public static void main(String[] args) {
try
{
int data=50/0; //may throw exception
// if exception occurs, the remaining statement will not exceute
System.out.println("rest of the code");
}
// handling the exception
catch(ArithmeticException e)
{
System.out.println(e);
}
}
}
Output:
java.lang.ArithmeticException: / by zero
Here, we can see that if an exception occurs in the try block, the rest of the block
code will not execute.
}
Output:
Can't divided by zero
Note: We can resolve the exception in a catch block to get normal termination.
public class Example6 {
public static void main(String[] args) {
int i=50;
int j=0;
int data;
try
{
data=i/j; //may throw exception
}
// handling the exception
catch(Exception e)
{
// resolving the exception in catch block
System.out.println(i/(j+2));
}
}
}
Output:
25
Note: We kept risky code along with try block, we also enclose exception code in
a catch block.
try
{
int data1=50/0; //may throw exception
}
// handling the exception
catch(Exception e)
{
// generating the exception in catch block
int data2=50/0; //may throw exception
}
System.out.println("rest of the code");
}
}
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
Here, we can see that the catch block didn't contain the exception code. So, enclose
exception code within a try block and use catch block only to handle the
exceptions.
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.
printStackTrace():
Stack trace
Description
Example:
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:
Example:
try
{
}
catch(Exception e)
default handler
Ex:
try{
a[5]=30/0;
catch(Exception e)
System.out.println("task1 is completed");
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)
catch(ArithmeticException e)
catch(SQLException e)
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(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.
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
All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.
class Test
try
System.out.println(10/0);
}
catch(Exception e)
e.printStackTrace();
catch(ArithmeticException e)
e.printStackTrace();
}}}
CE: Exception
class Test
main(String[] args)
try
System.out.println(10/0);
}
catch(ArithmeticException e)
e.printStackTrace();
catch(Exception e)
e.printStackTrace();
}}}
Output:
Compile successfully.
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)
Example 1
try
a[5]=30/0;
catch(ArithmeticException e)
catch(ArrayIndexOutOfBoundsException e)
}
catch(Exception e)
Output:
Example 2
try{
System.out.println(a[10]);
catch(ArithmeticException e)
catch(ArrayIndexOutOfBoundsException e)
catch(Exception e)
Output:
Example 3
In this example, try block contains two exceptions. But at a time only one
exception occurs and its corresponding catch block is invoked.
try{
a[5]=30/0;
System.out.println(a[10]);
catch(ArithmeticException e)
catch(ArrayIndexOutOfBoundsException e)
catch(Exception e)
}
}
Output:
Example 4
try{
String s=null;
System.out.println(s.length());
catch(ArithmeticException e)
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
catch(Exception e)
Output:
Example 5
Let's see an example, to handle the exception without maintaining the order of
exceptions (i.e. from most specific to most general).
class MultipleCatchBlock5{
try{
catch(Exception e){
catch(ArithmeticException e){
System.out.println("task1 is completed");
catch(ArrayIndexOutOfBoundsException e){
System.out.println("task 2 completed");
Output:
Compile-time error
The try block within a try block is known as nested try block in java.
Syntax:
....
try
statement 1;
statement 2;
try
statement 1;
statement 2;
catch(Exception e)
catch(Exception e)
}
....
class Excep6{
try{
try{
System.out.println("going to divide");
int b =39/0;
catch(ArithmeticException e){
System.out.println(e);
try{
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..");
Finally block:
Java finally block is a block that is used to execute important code such as closing
connection, stream etc.
Finally block in java can be used to put "cleanup" code such as closing a file,
closing connection etc.
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.
Note: If you don't handle exception, before terminating the program, JVM
executes finally block (if any).
Example:
try
{
risky code
}
catch(x e)
{
handling code
}
finally
{
cleanup code
}
The specialty of finally block is it will be executed always irrespective of whether
the exception raised or not raised and whether handled or not handled.
class Test{
try{
catch(ArithmeticException e){
System.out.println("catch block executed");
finally{
Output:
Ex:-
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{
public static void main(String[] args){
try{
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:
class Test{
public static void main(String[] args){
try{
System.out.println("try block executed");
System.out.println(10/0);
}
catch(NullPointerException e){
System.out.println("catch block executed");
}
Finally{
System.out.println("finally block executed");
}
}
}
Output:
Try block executed
Rule: For each try block there can be zero or more catch blocks, but only one
finally block.
Note: The finally block will not be executed if program exits(either by calling
System.exit() or by causing a fatal error that causes the process to abort).
return Vs finally:
Even though return statement present in try or catch blocks first finally will be
executed and 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{
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;
}
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){
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:
finally:
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.
Java final example
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;
}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();
}}
try{
stmt-1;
stmt-2;
stmt-3;
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;
Case 1: if there is no exception. 1, 2, 3, 4, 5, 6, 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 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 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.
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.
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);
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.
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.
Syntax:
throw exception;
Ex-1:-
Ex:-
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.
class Test{
public static void main(String[]args){
throw new ArithmeticException("/by zero");
}
}
In this case we are creating exception object explicitly and handover to the JVM
manually.
Note: In general we can use throw keyword for customized exceptions but not for
predefined exceptions.
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.
Ex:
class Test3{
static ArithmeticException e=new ArithmeticException();
public static void main(String[]args){
throw e;
}
}
Output:
Ex:
class Test3{
static ArithmeticException e;// not referring any object
public static void main(String[] args){
throw e;
}
}
Output:
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");
}
}
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();
}
}
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{
out.println("hello");
CE:
Example:
class Test3{
Thread.sleep(5000);
return_type method_name() throws exception_class_name{
//method code
}
We can handle this compile time error by using the following 2 ways.
class Test3{
public static void
main(String[] args){
try{
Thread.sleep(5000);
}
catch(InterruptedException e){
}
}
}
Output:
Successfully
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{
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:
Case1:You caught the exception i.e. handle the exception using try/catch.
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.*;
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.
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.
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 exception
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{
throw new IOException("device error");
}
}
class Testthrows4{
public static void main(String args[])throws IOException{//declare exception
M m=new M();
m.method();
System.out.println("normal flow...");
}
}
Output:Runtime Exception
Note :
Example:
class Test{
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:
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:
Case 2:Example:
class Test3{
public static void main(String[] args){
throw new Exception();
}
}
Output:
Ex:
class Test3{
public static void main(String[] args){
throw new Error();
}
}
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:
Case 4:
We can use throws keyword only for constructors and methods but not for classes.
Example:
Exception handling keywords summary:
7. Incompatible types.
found:Test requried:java.lang.Throwable;
8. Unreachable statement
If you are creating your own Exception that is known as custom exception or user-
defined exception. Java custom exceptions are used to customize the exception
according to user need.
By the help of custom exception, you can have your own exception and message.
Example:
1. InSufficientFundsException
2. TooYoungException
3. TooOldException
Ex:-
InvalidAgeException(String s){
super(s);
}
class TestCustomException1{
if(age<18)
else
System.out.println("welcome to vote");
try{
validate(13);
catch(Exception m){
Output:
Program:
TooYoungException(String s){
super(s);
TooOldException(String s){
super(s);
class CustomizedExceptionDemo{
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{
}}}
Output:
>java CustomizedExceptionDemo 61
at CustomizedExceptionDemo.main(CustomizedExceptionDemo.java:21)
>java CustomizedExceptionDemo 27
>java CustomizedExceptionDemo 9
at CustomizedExceptionDemo.main(CustomizedExceptionDemo.java:25)
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).
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{
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{
m2();
m1();
M1();
Output:
Run time error: StackOverFloeError
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:
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{
}
Output:
Runtime exception:
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
t.setPriority(100);//invalid---Thread priority in b/w 1to 10 only
}}
Output:
Runtime exception
8. NumberFormatException:
Example:
class Test{
int i=Integer.parseInt("10");
int j=Integer.parseInt("ten");
}}
Output:
Runtime Exception
Ex:
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)
4. AE(AssertionError)
import java.io.*;
class Parent{
void msg(){
System.out.println("parent");
System.out.println("TestExceptionChild");
}
p.msg();
import java.io.*;
class Parent{
void msg(){
System.out.println("parent");
System.out.println("child");
}
p.msg();
Output:child
import java.io.*;
class Parent{
System.out.println("child");
}
public static void main(String args[]){
try{
p.msg();
catch(Exception e){
import java.io.*;
class Parent{
System.out.println("parent");
try{
p.msg();
catch(Exception e){
Output: child
import java.io.*;
class Parent{
System.out.println("parent");
System.out.println("child");
try{
p.msg();
catch(Exception e){
Output:child
import java.io.*;
class Parent{
System.out.println("parent");
}
class TestExceptionChild5 extends Parent{
void msg(){
System.out.println("child");
try{
p.msg();
catch(Exception e){
Output:child