java Exceptions:• An Exception is an abnormal and unexpected and also unwanted event that disturbs the normal flow of the program.
Ex: FileNotFoundException
ArithmaticException etc..
Default Exception Handling Mechanism in JAVA:
class Sample
{
public static void main(String a[])
{
doStuff();
}
public static void doStuff()
{
doMoreStuff();
}
public static void doMoreStuff()
{
System.out.println(“hai”);
System.out.println(10/0);
}
}
Output: hai
RTE: Exception in thread “main” Java.Lang.Arithematic Exception: /by zero
At Sample . doMoreStuff(Sample.java)
At Sample . doStuff(Sample.java:9)
At sample . main(Sample. java :5)
• If an exception is raised inside any method is r3esponsible for the creation of exception object. (here doMoreStuff() is responsible )
• The Exception object must contain the fallowing information.
1. Name of the Exception(Java.Lang.ArithematicException)
2. Description of the Exception (/ by zero)
3. The position at which the exception raised. (stack trace).
• Now the method handover that exception object to the JVM. JVM will come with that exception object and it will check, is there any exception object and it will check is there any exception handler inside that method abnormally and removes the corresponding entry from the stack.
• Now the method handover that exception object to the JVM. JVM will come with that exception object and it will check, is that any exception handler inside that method. If there is no exception handler then JVM blindly terminate that method abnormally and removes the corresponding entry from the stack.
• JVM will check for the caller(doStuff()) containing any exception handling code. If the caller also doesn’t contain any exception handling code, then JVM simply terminate that method also and remove the corresponding entry from the stack.
• This process will continue, until main() method. If the main() also doesn’t have any exception handling code then JVM terminates main() abnormally and handover the responsibility of the exception handling to default exception handler.
• Now Default Exception handler print the exception information to the end user
Checked vs
Unchecked Exceptions :
• The Exceptions which are checked by the compiler for smooth execution of program at Runtime are called checked Exceptions.
• The Exceptions which are unable to check by the compiler are called Unchecked Exceptions.
• Runtime Exception and its child classes: Error and its child classes are Unchecked Exceptions. While the remaining all are Unchecked Exceptions.
Partially Checked vs
Fully Checked :
A Checked Exception is said to be Fully Checked Exception if and only if all its child classes are also checked. Otherwise it is Partially Checked Exception.
Ex: IOException is Fully Checked Exception
Exception is Partially Checked
Throwable is Partially Checked
We can handle exceptions by using the fallowing keywords.
1).
try 2).
catch 3).
Finally 4).
throw 5).
throwstry
{
//Risky code
}
catch(XException e)
{
//Define the handler
}
Ex:
try
{
System.out.println(10/0);
}
catch(ArithematicException e)
{
System.out.println(“caught”);
System.out.println(10/2);
}
System.out.println(“hello”);
output:
caught
5
hello
try
{
Statement 1;
Stmt 2;
Stmt 3;
}
catch(XException e){ Statement 4; }
stmt5;
Case 1:- If there is no Exception ->1,2,3,5 are executes. So normal termination.
Case 2:- If an Exception raised at stmt2 and the corresponding catch block found then 1 fallowed 4,5 are executes. So, normal termination.
Case 3:- If an Exception is raised at stmt2, but the corresponding catch block not found. Then stmt1 fallowed by abnormal termination.
Case 4:- If an Exception raised at stmt2 and the corresponding catch block found; but while executing catch block raises another Execution then stmt1 fallowed by abnormal termination.
Methods For Displaying Error Information :
The class Throwable contains the fallowing methods for displaying Error information.
1.
printStackTrace():
Name of the Exception: Description of Exception Stack trace.
catch(ArithmaticException e)
{
e.printStackTrace();
}
System.out.println(“hai..”);
output:
java.lang.ArithmaticException: /by zero at sample.main(Sample.java)
Hai
2. public String toString(): Name of the Exception: Description of Exception
catch(ArithmaticException e)
{
System.out.println(e.toString());
}
System.out.println(“hai..”);
output:
java.lang.ArithmaticException: /by zero
Hai
3. public String getMessage(): Description of Exception
catch(ArithmaticException e)
{
System.out.println(e.getMessage());
}
System.out.println(“hai..”);
output: /by zero
hai
Try with Multiple catch blocks:
• The way of handling the exception is varied from exception to exception, hence it is a good programming practice to keep separate catch block for every exception.
try
{
System.out.println(10/0);
}
catch(ArithmeticException e) //child
{
//code
}
catch(Exception e) //parent
{
//code
}
Valid since child --> parent
try
{
System.out.println(10/0);
}
catch(Exception e) //parent
{
//code
}
catch(ArithmeticException e) //child
{
//code
}
InValid since parent ----> child
compile time error(CTE) : Exception has already been caught by catch (
ArithmeticException e)
• If multiple catch blocks are defined for the try statement, the order of the catch blocks is important. We should take the catch blocks from child to parent, violation leads to CTE saying “Exception” has already been caught”.
Control Flow in try with multiple catch blocks:
try
{
Statement 1;
Stmt2;
Stmt3;
}
catch(XException e)
{
Stmt 4;
}
catch(YException e1)
{
Stmt 5;
}
Stmt6;
Case 1:- If there is no Exception ->1,2,3,6 is executes. So normal termination.
Case 2:- If an Exception raised at stmt2 and the corresponding catch block(Y Exception e1) is matches then 1,5,6 are executes. So, normal termination.
Case 3:- If an Exception is raised at stmt2, but the corresponding catch block not found. Then stmt1 fallowed by abnormal termination.
Control Flow in Nested try catch :
try
{
Statement 1;
Stmt2;
Stmt3;
try
{
Stmt4;
Stmt5;
Stmt6;
}
catch(XException e)
{
Stmt7;
}
Stmt8;
}
catch(YException e)
{
Stmt9;
}
Stmt10;
Case 1:- If there is no Exception ->1, 2, and 3,4,5,6,8,10 is executes. So normal termination.
Case 2:- If an Exception raised at stmt2 and the corresponding catch block is matches then 1,9,10 are executes. So, normal termination.
Case 3:- If an Exception raised at stmt2 and the corresponding catch block not found. 1 fallowed by abnormal termination.
Case 4:- If an Exception raised at stmt5 and the corresponding catch block is matches then 1,2,3,4,7,10 and Normal Termination.
Case 5:- If an Exception raised at stmt5 and the corresponding catch block is not matched but outer catch block has matched 1,2,3,4,9,10 and Normal Termination.
Case 6:- An Exception raised at stmt2 and the corresponding catch block has matched but while executing that catch block another exception raised then fallowed by abnormal termination.
Case 7:- An Exception raised at stmt8 and the corresponding catch block has matched then 1,2,3,9,10 fallowed by Normal Termination. If the catch block has not matched abnormal termination.
finally block: try
{
System.out.println(10/0);
}
catch(AE e)
{
System.out.println(“catch”);
}
finally
{
System.out.println(“catch”);
}
• The cleanup code, we have to keep inside finally block because irrespective of exception occurred or not occurred or handled or not handled, the finally block will always execute.
Q: Difference between final, finally and finalize?• It is highly recommended to keep cleanup code inside finally block instead of finalize().
• The finally block will always execute except the place where the JVM got shutdown. We can shutdown the JVM by calling /using System.exit(0).
Ex:
try
{
System.out.println(“hai”);
}
catch(
NULL pointer exception e)
{
System.out.println(“catch”);
}
finally
{
System.out.println(“finally”);
}
output:
hai
finally
Q). 1. try{} catch(X e){} -->valid
2. try{}catch(X e){}finally{} -->valid
3. try{}finally{}catch(X e){} --> invalid
4. try{}finally{} -->valid
Ie., try --> catch --> finally is the only order.
Only try{} --->invalid,
Only catch{} ----> invalid
Only finally{} ---->invalid
Note: try without catch & catch with out try invalid
Ex:
catch(..){}
finally{}
CTE: catch with out try
Control Flow in try, catch, finally block :
try
{
Stmt1;
Stmt2;
Stmt3;
}
catch(XException e)
{
Stmt 4;
}
finally
{
Stmt 5;
}
Stmt 6;
Case 1:- If there is no exception then 1,2,3,5,6 and normal termination.
Case 2:- If an exception raised at stmt2 and the corresponding catch block found 1,4,5,6 and normal termination.
Case 3:- If an exception raised at stmt2 and the corresponding catch block not matched 1,5 and abnormal termination.
Control Floe in the Nested try, catch, finally blocks:try
{
Stmt1;
Stmt2;
Stmt3;
try
{
Stmt4;
Stmt5;
Stmt6;
catch(XException e)
{
Stmt 7;
}
finally
{
Stmt 8;
}
Stmt 9;
}
catch(YException 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 and normal termination.
Case 2: If an exception raised at stmt 2 and the corresponding catch block found then 1,10,11,12 and normal termination.
Case 3: If an exception raised at stmt2 and the corresponding catch block has not matched then 1,11 and abnormal termination.
Case 4: If an exception raised at stmt5 and the corresponding catch block has matched then 1,2,3,4,7,8,9,11,12 and normal termination.
Case 5: If an exception raised at stmt5 and the corresponding catch block has not matched but the outer catch has matched then 1,2,3,4,8,10,11,12 and normal termination.
Case 6: If an exception raised at stmt5 but the inner and outer catch blocks are not matched then 1,2,3,4,8,11 and abnormal termination.
‘Throw’ keyword:
public static void main(String a[])
{
try
{
Throw new AithmeticException()
}
}
By using ‘throw ‘ keyword, over created customized exception objects are handed over to JVM.
Ex:class Sample
{
public static void main (String a[])
{
throw new ArithmeticException();
System.out.println(“hai”);
}// CTE: Unreachable statement
}
After throw we are not allowed to keep any stmt, violation leads to CTE saying “unreachable statement”.
Ex:class Sample
{
static ArithmeticException e;
public static void main(String[] a)
{
throw e; //invalid
}
}
output: NullPointerException
‘e’(is in instance area) is not pointing “ArithmeticException’ here.
static ArithmeticException e=new ArithmeticException();
Ex:class Sample
{
public static void main(String a[])
{
Throw new Exception(); //invalid
}
}//CTE: “Unreported Exception Java.lang.Exception must be caught” or declared to be thrown.
• Inside a program if there is any chance of throwing a checked exception explicitly or implicitly we have to handle that checked exception by using try - catch or we have to delegate the responsibility or exception handling to the caller. Violation leads to CTE saying Unreported Exception xxx; must be caught or declared to be thrown.
“throws” Keyword :
Ex:class Sample
{
public static void main(String a[])throws InteruptedException
{
doStuff();
}
public static void doStuff()throws IE
{
doMoreStuff();
}
public static void doMoreStuff()
{
System.out.println(“hai”);
Thread.sleep(1000);
}
}
without ‘throws’ CTE: Unreported Exception java.lang.interuptedException ; must be caught or declared to be thrown. To avoid CTE another way in using try ---> catch block.
Ex: class Sample
{
public static void main(String a[])
{
try
{
System.out.println(“hello”);
}
catch(ArithmaticException e){}-->no CTE
}
}
class Sample
{
public static void main(String a[])
{
try
{
System.out.println(“hello”);
}
catch(IOException e){} --->CTE (fullychecked exception)
}
}
CTE: exception java.io.IOException is never thrown in the body of the corresponding try statement.
We can ‘throws’ keyword for delegating the responsibility of the Exception handling to the caller.
If we are keeping the catch block for fully checked exception there should may be a chance of raising exception in the corresponding try block otherwise CTE saying XXXException is never thrown in the body of corresponding try statement.
Case 1: try
{
System.out.println(“hai”);
}
catch(ArithematicException e) //valid no CTE
{ //unchecked exception }
Case 2: try
{
System.out.println(“hai”);
}
catch(Exception e) //valid no CTE
{ //Partially checked exception }
Case 3: try
{
System.out.println(“hello”);
}
catch(IOException e) //invalid CTE
{ // fully checked exception }
Customized Exceptions :
Based on the programming required sometimes we have to design our own Customized Exceptions.
Ex: Insufficient funds Exception
too young Exception
too old Exception
class TooYoungException extends RunTimeException
{
TooYoungException(String s)
{
super(s);
}
Class Sample
{
public static void main(String a[])
{
Int i=Integer.parseInt(arg[0]);
If(i>85)
throw new TooYoungException(“please wait some more time, you eill get married”);
else if(i<10)
throw new TooYoungException(“ur age is already crossed”);
else
throw new TooYoungException(“very soon you will get match”);
}
}
CommonExceptions and Errors:Exceptions or errors may be thrown by either JVM(JVM Exceptions) or thrown explicitly by application developers or API programmers(programmatic exception).
1.
NULLPOINTER EXCEPTION: Class Sample
{
Static int[] a;
Static String name;
public static void main(String a[])
{
System.out.println(a.length);
}
}
System.out.println(a[o]); // null pointer exception (NPE)
System.out.println(name.length); //NPE
This is child class of RuntimeException. It is unchecked exception.
This is thrown by JVM when attempting to acess an object with a reference variable whose current value is null.
Ie., on null if we are applying any operation we will get NullPointerException.
2. STACK OVERFLOW ERROR:-• This is child class of virtual machine error.
• It is unchecked
Throwable ----> Error ---> VMError ---> StackOverFlowError
class Sample
{
public static void m1()
{
m1();
}
public static void main(String a[]){ m1(); } // stack overflow error
}
StackOverflow error is thrown by JVM when a method recurses too deeply.
class Sample
{
Sample() { new Sample(); }
public static void main(String a[]) { Sample s= new Sample(); }//Exception in main thread stack overflow error
}
3. ARRAY INDEXOUTOF BOUNDS EXCEPTION:
• This is a child class of IndexOutOfBoundsExcption.
Throwable ---> Exception ---> RunTimeException ----> IndexOutOfBoundsException---> ArrayIndexOutOfBoundsException, StingIndexOutOfBoundsException
• It is an unchecked exception thrown by JVM when we are accessing an array element with
Invalid index.
Ex:
class Sample
{
public static void main(String a[])
{
Int[] a=new int[6];
System.out.println(a[5]); //0
System.out.println(a[7]); //RTE: ArrayIndexOutOfException
System.out.println(a[-2]); //----do----
System.out.println(a[-2.5]); //CTE: PLP req: int found:double
}
}
4. CLASS CAST EXCEPTION:Class Sample
{
public static void main(String a[]))
{
String s=”anu”;
Object o=(Object)s;
String s1=(String)O;
System.out.println(“hai”);
}
}
• It is the child class of RTE
• It is unchecked exception, thrown by JVM when attempting to cast a reference variable to a type the fails to cast a reference variable to a type the faith the IS- A test.
----> Object o=new Object();
String s=(String)o; // Class Cast Exception
----> StringBuffer s1= (StringBuffer)s;
5.
NOCLASS DEF FOUND ERROR:- It is the child class of error and it is unchecked one and unreachable.
- It is thrown by JVM. If the JVM or class loader tries to load the definition of the class and no definition of the class could be found.
6.
EXCEPTION IN INITIALIZER ERROR:
class Sample
{
Static String s;
String s1=new String(s);
public static void main(String a[])
{
System.out.println(“hai”);
}
}//Exception in initializer error caused by java.lang.NullPointerException.
Thrown by the JVM to indicate that an exception is occur during initialization of static variable or initialization block.
7. ILLEGAL ARGUMENT EXCEPTION:- It extends RTE and unchecked.
- Thrown by aPI developer to indicate that a method has been passed an illegal or inappropriate argument.
Ex: Thread class setPriority() and sleep() methods throw this exception.
class Sample
{
p s v m(String a[])
{
Thread.currentThread().setPriority(15);
}
}//CTE: Illegal Argument exception
8. NumberFormatException: Integer i=new Integer(“10”);//valid
Integer i=new Integer(“ten”);//invalid
CTE: NumberFormateException
int i=Integer.parseInt(arg[0]);
In commandline if we give “10” is valid. But “ten” is invalid.
It is the direct child class of illegal argument exception and thrown programmatically to indicate the application has attempted to convert a string to the number, but the string doesn’t have appropriate format.
9.
IllegalStateException: It extends RTE and indicates that a method has been invoked at an illegal or inappropriate time.
Ex: PrintWriter out=res.getWriter();
Out.println(…);
Out.close();
Out.println(“…”); ---> this is not appropriate time to call print() on out object and hence throws IllegalStateException.
10. Assertion Error: It is the child class of error throws programatically when assert statement when Assert statement fails.
Summarization:Exception or error ---------------------
thrown by1. NullPointerException ------------------ JVM
2. StackOverFlowErrorException --------------- JVM
3. ArrayIndexOutOfBoundsException ------------- JVM
4. ClassCastException ------------------------- JVM
5. NoClassDefFoundError -------------------- JVM
6. ExceptionInIntializerError -------------------- JVM
thrown by programmatically by programmer API developer:
7. IllegealArgumentException
8. NumberFormatException
9. IllegalStateException
10. Assertion Error