Introduction
An unexpected unwanted event that disturbs normal flow of program is exception. It is highly recommended to handle exceptions. The main objective of exception handling is graceful termination of the program.
Runtime Stack mechanism
For every thread, jvm creates a runtime stack. Each and every method call performed by the thread will be stored in the corresponding stack. Each entry in stack is called activation record/stack frame. After completing every method call, corresponding entry from the stack will be removed. After completing all method calls, stack will become empty. The empty stack will be destroyed by jvm just before terminating the thread.
eg: Step1: jvm creates a run time stack for main thread. Inserts(push) main(), subFunction1(), subFunction2() and so. Pops the stack as the execution is complete.
Default exception handling in java
Example:
class Demo{
public static void main(String args[]){
subFunction1();
}
public static void subFunction1(){
subFunction2()
}
public static void subFunction2(){
int a=5/0;
}}
Exception hierarchy
Checked exceptions:- Exceptions which are checked by compiler(whether programmer handled or not) for smooth execution of program at runtime are called Checked exceptions. Programmer should handle all such exceptions.
eg:
import java.io.*;
Class TestException{
public static void main(String args[]){
PrintWriter pw=new PrintWriter("file11.txt");
pw.print("Hello World");
}
}
Compiler will throw: Unreported exception java.io.FileNotFoundException must be caught or declared to be thrown
RuntimeExceptions and its child classes are unchecked, Error and its child classes are unchecked. Except these remaining are CHECKED.
Fully Checked vs Partially Checked
Fully Checked means all Excpetions and its child classes are checked
Customized exception handling by using try-catch
The code which may raise exception is called risky code, and we have to define that code inside TRY block. Corresponding handling code, we have to define inside Catch block.
try{
risky code;
}catch(Exception e){
handling code;
}
try{
stmt1;
stmt2;
stmt3;
}catch(Exception e){
stmt 4;
}
stmt5;
Any where exception is raised, rest of try block will not be executed. Hence length of try block should be as less as possible.
If exception occurs at stmt 4 or 5(not part of try block), it will be an abnormal termination
There may be chance of raising an exception inside catch and finally blocks.
Different methods to get Exception information.
Throwable class defines following methods to print Exception information
printStackTrace(): - Use the method to get Name of exception, description & stack Trace
toString() :- Use the method to get Name of exception and description
getMessage():- Use the method to get description.
Class Test{
public static void main(String args[]){
try{
System.out.println(10/0);
} Catch(ArthimematicException e){
e.printStackTrace();
System.out.println(e); // System.out.println(e.toString());
System.out.println(e.getMessage());
}
}}
Default exception handler uses printStackTrace() to print exception information
If try with multiple catch blocks present then the order of catch blocks is important. Child should be present first then child, other wise it will be compile time error. "Exception XXX has already been caught"
difference between final, finally, finalize
final
final - It is a modifier applicable for classes, methods and variables
finally is a block, always associated with try-catch to maintain clean up code. The block will be executed always irrespective of whether exception is raised/not raised and handled/not handled.
try{
risky code;
}catch(Exception e){
handling code;
}
finally {
clean up code;
}
finalize()
It is a method, always invoked by Garbage Collector, just before destroying object, to perform clean up activities. Garbage collector destroys object once the finalize method is executed.
finally block is responsible to perform clean up activities related to try-block i.e what ever resources we opened as part of try block will be closed inside finally block.
finalize() method is responsible to perform clean up activities related to object ie what ever resources associated with object will be deallocated before destroying an object by using finalize().
Points to note:
Either catch or finally has to be associated with try block, else it will be a compile time error.
try block with out catch and having finally block is valid. However it will be abnormal termination.
throw keyword
It is to hand programmatically created Exception object to jvm manually. It is useful for user defined/custom exceptions. It can be used only for Throwable types.
throws keyword
In a program, if there is a possibility of raising checked of exception, then we should handle the checked exception. Otherwise, compile time will be raised saying, "Unreported Exception XXX must be caught or declared to be thrown".
Throws key word can be used to delegate responsibility of exception handling to caller of the method. The caller could be either jvm or another method.
Throws key word required only for checked exception. No impact for unchecked exceptions.
Throws key word is just to avoid compile time exception. It doesn't prevent abnormal termination of program.
Throws key word for class is invalid. It can be used for methods & constructors.
Within Try block, if there is no chance of raising an exception then adding catch block for fully checked exception will raise compile time error, "Exception ABC is never thrown in the body of corresponding try statement".
Customized or user defined exceptions
These are exceptions defined by programmer to meet programming requirements.
Class MyException extends RuntimeException
{
MyException(String str){
super(str);
}
}
Throw key word is best suitable for user defined or custom exceptions but not for pre defined exceptions. It is recommended to define custom exceptions as unchecked(extend runtime exception).
Top-10 exceptions
Exceptions are divided into 2 categories jvm exceptions & programmatic exception
Exceptions raised automatically by jvm when ever a particular event occurs are jvm exceptions
eg: ArthimaticException, NullPointerException,
Exceptions which are raised explicitly either by programmer or api developer are programmatic exceptions.
eg: IllegalArgumentException
ArrayIndexOutOfBoundsException- When array is accessed with out of range index
NullPointerException - When any operation is performed on NULL
ClassCastException- When we try to typecast parent object to child type
StackOverflowError-Caused by unconditional recursive method call
NoClassDefFoundError- When jvm fails to find .class file
ExceptionInInitializerError- The exception is raised when ever there is error while executing static blocks or static variable assignments.
Class test{
static int a=10/0 // ExceptionInIntializerError caused by Arthimatic exception.
}
Class test{
static{
String s=null;
system.out.println(s.length); /// ExceptionInIntializerError caused by NullPointerException
}
}
IllegalArgumentException- Raised explicitly either by programmer or by api developer to indicate a method has been invoked with illegal argument.
Thread t=new Thread()
t.setPriority(15); // valid range is 0 to 10
NumberFormatException- It is child of IllegalArgumentException. Raised explicitly either programmer or api developer when attempting to convert String that is not properly formatted to Number.
int i = Integer.parseInt("adf");
IllegalStateException- Raised explicitly either by programmer or by api developer to indicate a method has been invoked wrong time.
Thread t = new Thread();
t.start();
t.start(); // IllegalThreadStateException
AssertionError- It is child of Error. Raised explicitly either by programmer or by api developer to indicate Assert statement failed.
assert(x>10);
1.7 version enhancements
try with resources
try(BufferredReader br = new BufferredReader(new FileReader("input.txt")))
{
//application logic
}
catch(Exception e)
{
}
br will be closed automatically once control reaches end of try block either normally or abnormally. Programmer is not responsible to close explicitly.
eg: multi resources
try(FileReader fr = new FileReader("input.txt"); FileWriter fr = new FileWriter("output.txt"))
{
//application logic
}
NOTE: The resources(in try) should be autoCloseable. A resource is autoCloseable if corresponding class implements java.lang.AutoCloseable interface
All I/O resources, DB resources and Network related resources are already implemented AutoCloseable interface. AutoCloseable interface contains only one method public void close()
All resource reference variables which are declared as try block are implicitly final. Hence, within try block reassignment is not possible.
Until java 1.6, try should be associated with either catch or finally. From 1.7 onwards, only try with resource with out catch or finally.
try(R)
{
}
Finally block is not required as resources will be closed implicitly.
multi-catch block
Until java1.6, even though multiple different exceptions having same handling code, for every exception type, we have to write a separate catch block. It increases length of code and reduces readability.
Multi-catch block introduced in 1.7 version. Single catch block can handle multiple different type of exceptions.
try{
}
catch(ArthimaticException | IOException e)
{
e.printStackTrace();
}
catch(NullPointerException | InteruptionException e)
{
e.getMessage();
}
In multi catch block, there should not be any relation between Exception types(Parent-Child).
Inside a method when exception handling is not done and when an exception is raised , the exception object will be propagated to caller. Then caller method is responsible to handle exception. This process is called Exception Propagation.
re throwing exception: Use the approach to convert one exception type to another exception.
try {
}
catch(ArthimaticException e){
throw new nullPointerExcepion();
}
An unexpected unwanted event that disturbs normal flow of program is exception. It is highly recommended to handle exceptions. The main objective of exception handling is graceful termination of the program.
Runtime Stack mechanism
For every thread, jvm creates a runtime stack. Each and every method call performed by the thread will be stored in the corresponding stack. Each entry in stack is called activation record/stack frame. After completing every method call, corresponding entry from the stack will be removed. After completing all method calls, stack will become empty. The empty stack will be destroyed by jvm just before terminating the thread.
eg: Step1: jvm creates a run time stack for main thread. Inserts(push) main(), subFunction1(), subFunction2() and so. Pops the stack as the execution is complete.
Default exception handling in java
- When an exception occurs, the respective method in which it is raised, is responsible to create Exception Object by including Name of exception, Description of exception, location at which exception occurred(Stack Trace)
- After creating exception object method hand overs the object to the jvm.
- jvm will check whether the method contains exception handling code. If method doesn't contain exception handling code, then jvm terminates the method abnormally and remove the corresponding failed method entry from run time stack of method calls.
- Jvm identifies the called method, and checks for Exception handling code. If NOT exits, it will terminate abnormally and remove the corresponding method entry from stack
- The above process will be continued until main method. If main method also does not contain handling code, then jvm terminates the main() abnormally and removes the entry from stack.
- JVM will then handover the control/responsibility of exception handling to default exception handler which is the part of jvm, by passing the Exception object.
- Default exception handler prints the exception information to console, and terminates the program abnormally.
- Default exception handler prints exception information in following format:
- <exception thread>:<exception name>:<exception description> followed by stack trace
- eg: Exception in thread main(): java.lang.ArthimaticException:division by zero
- at Demo.subFunction2()
- at Demo.Funtion1()
- at Demo.main()
Example:
class Demo{
public static void main(String args[]){
subFunction1();
}
public static void subFunction1(){
subFunction2()
}
public static void subFunction2(){
int a=5/0;
}}
Exception hierarchy
- Throwable class acts as root for java exception hierarchy
- Throwable class defines 2 child classes, Exception and Error.
- Exception
- Most of the time exceptions are caused by our program. These are recoverable. eg: remote file not found
- RuntimeException
- ArthimeticException
- NullPointerException
- IndexOutOfBoundsException
- ArrayIndexOutOfBoundException
- StringIndexOutOfBoundException
- IllegalArgumentException
- NumberFormatException
- IOException
- EndOfFileException
- FileNotFoundException
- InterruptedIOException
- ServletException
- RemoteException
- InterruptedException..
- Error: Most of the times, errors are NOT caused by our program. These are due to lack of system resources. These are non-recoverable. eg: stack overflow error or out of memory error
- VirtualMachineError
- StackOverflowError
- OutOfMemoryError
- AssertionError
- ExceptionInInitializerError
Checked exceptions:- Exceptions which are checked by compiler(whether programmer handled or not) for smooth execution of program at runtime are called Checked exceptions. Programmer should handle all such exceptions.
eg:
import java.io.*;
Class TestException{
public static void main(String args[]){
PrintWriter pw=new PrintWriter("file11.txt");
pw.print("Hello World");
}
}
Compiler will throw: Unreported exception java.io.FileNotFoundException must be caught or declared to be thrown
RuntimeExceptions and its child classes are unchecked, Error and its child classes are unchecked. Except these remaining are CHECKED.
Fully Checked vs Partially Checked
Fully Checked means all Excpetions and its child classes are checked
Customized exception handling by using try-catch
The code which may raise exception is called risky code, and we have to define that code inside TRY block. Corresponding handling code, we have to define inside Catch block.
try{
risky code;
}catch(Exception e){
handling code;
}
try{
stmt1;
stmt2;
stmt3;
}catch(Exception e){
stmt 4;
}
stmt5;
Any where exception is raised, rest of try block will not be executed. Hence length of try block should be as less as possible.
If exception occurs at stmt 4 or 5(not part of try block), it will be an abnormal termination
There may be chance of raising an exception inside catch and finally blocks.
Different methods to get Exception information.
Throwable class defines following methods to print Exception information
printStackTrace(): - Use the method to get Name of exception, description & stack Trace
toString() :- Use the method to get Name of exception and description
getMessage():- Use the method to get description.
Class Test{
public static void main(String args[]){
try{
System.out.println(10/0);
} Catch(ArthimematicException e){
e.printStackTrace();
System.out.println(e); // System.out.println(e.toString());
System.out.println(e.getMessage());
}
}}
Default exception handler uses printStackTrace() to print exception information
If try with multiple catch blocks present then the order of catch blocks is important. Child should be present first then child, other wise it will be compile time error. "Exception XXX has already been caught"
difference between final, finally, finalize
final
final - It is a modifier applicable for classes, methods and variables
- When a class is declared as final, then it is not allowed to extend the class i.e not allowed to create child class for it(inheritance not possible)
- When a method is declared as final, it is not allowed to override in child class
- When a variable is declared as final, it is not allowed to change the value assigned.
finally is a block, always associated with try-catch to maintain clean up code. The block will be executed always irrespective of whether exception is raised/not raised and handled/not handled.
try{
risky code;
}catch(Exception e){
handling code;
}
finally {
clean up code;
}
finalize()
It is a method, always invoked by Garbage Collector, just before destroying object, to perform clean up activities. Garbage collector destroys object once the finalize method is executed.
finally block is responsible to perform clean up activities related to try-block i.e what ever resources we opened as part of try block will be closed inside finally block.
finalize() method is responsible to perform clean up activities related to object ie what ever resources associated with object will be deallocated before destroying an object by using finalize().
Points to note:
Either catch or finally has to be associated with try block, else it will be a compile time error.
try block with out catch and having finally block is valid. However it will be abnormal termination.
throw keyword
It is to hand programmatically created Exception object to jvm manually. It is useful for user defined/custom exceptions. It can be used only for Throwable types.
throws keyword
In a program, if there is a possibility of raising checked of exception, then we should handle the checked exception. Otherwise, compile time will be raised saying, "Unreported Exception XXX must be caught or declared to be thrown".
Throws key word can be used to delegate responsibility of exception handling to caller of the method. The caller could be either jvm or another method.
Throws key word required only for checked exception. No impact for unchecked exceptions.
Throws key word is just to avoid compile time exception. It doesn't prevent abnormal termination of program.
Throws key word for class is invalid. It can be used for methods & constructors.
Within Try block, if there is no chance of raising an exception then adding catch block for fully checked exception will raise compile time error, "Exception ABC is never thrown in the body of corresponding try statement".
Customized or user defined exceptions
These are exceptions defined by programmer to meet programming requirements.
Class MyException extends RuntimeException
{
MyException(String str){
super(str);
}
}
Throw key word is best suitable for user defined or custom exceptions but not for pre defined exceptions. It is recommended to define custom exceptions as unchecked(extend runtime exception).
Top-10 exceptions
Exceptions are divided into 2 categories jvm exceptions & programmatic exception
Exceptions raised automatically by jvm when ever a particular event occurs are jvm exceptions
eg: ArthimaticException, NullPointerException,
Exceptions which are raised explicitly either by programmer or api developer are programmatic exceptions.
eg: IllegalArgumentException
ArrayIndexOutOfBoundsException- When array is accessed with out of range index
NullPointerException - When any operation is performed on NULL
ClassCastException- When we try to typecast parent object to child type
StackOverflowError-Caused by unconditional recursive method call
NoClassDefFoundError- When jvm fails to find .class file
ExceptionInInitializerError- The exception is raised when ever there is error while executing static blocks or static variable assignments.
Class test{
static int a=10/0 // ExceptionInIntializerError caused by Arthimatic exception.
}
Class test{
static{
String s=null;
system.out.println(s.length); /// ExceptionInIntializerError caused by NullPointerException
}
}
IllegalArgumentException- Raised explicitly either by programmer or by api developer to indicate a method has been invoked with illegal argument.
Thread t=new Thread()
t.setPriority(15); // valid range is 0 to 10
NumberFormatException- It is child of IllegalArgumentException. Raised explicitly either programmer or api developer when attempting to convert String that is not properly formatted to Number.
int i = Integer.parseInt("adf");
IllegalStateException- Raised explicitly either by programmer or by api developer to indicate a method has been invoked wrong time.
Thread t = new Thread();
t.start();
t.start(); // IllegalThreadStateException
AssertionError- It is child of Error. Raised explicitly either by programmer or by api developer to indicate Assert statement failed.
assert(x>10);
1.7 version enhancements
try with resources
try(BufferredReader br = new BufferredReader(new FileReader("input.txt")))
{
//application logic
}
catch(Exception e)
{
}
br will be closed automatically once control reaches end of try block either normally or abnormally. Programmer is not responsible to close explicitly.
eg: multi resources
try(FileReader fr = new FileReader("input.txt"); FileWriter fr = new FileWriter("output.txt"))
{
//application logic
}
NOTE: The resources(in try) should be autoCloseable. A resource is autoCloseable if corresponding class implements java.lang.AutoCloseable interface
All I/O resources, DB resources and Network related resources are already implemented AutoCloseable interface. AutoCloseable interface contains only one method public void close()
All resource reference variables which are declared as try block are implicitly final. Hence, within try block reassignment is not possible.
Until java 1.6, try should be associated with either catch or finally. From 1.7 onwards, only try with resource with out catch or finally.
try(R)
{
}
Finally block is not required as resources will be closed implicitly.
multi-catch block
Until java1.6, even though multiple different exceptions having same handling code, for every exception type, we have to write a separate catch block. It increases length of code and reduces readability.
Multi-catch block introduced in 1.7 version. Single catch block can handle multiple different type of exceptions.
try{
}
catch(ArthimaticException | IOException e)
{
e.printStackTrace();
}
catch(NullPointerException | InteruptionException e)
{
e.getMessage();
}
In multi catch block, there should not be any relation between Exception types(Parent-Child).
Inside a method when exception handling is not done and when an exception is raised , the exception object will be propagated to caller. Then caller method is responsible to handle exception. This process is called Exception Propagation.
re throwing exception: Use the approach to convert one exception type to another exception.
try {
}
catch(ArthimaticException e){
throw new nullPointerExcepion();
}
No comments:
Post a Comment