Exception Handling
Exception Handling
-Exception is an error that can happen during the execution of program and can break its normal flow.
-Whenever exception occurs while executing a program, an exception object is created and then JRE tries to call exception handler to
handle exception.
-If suitable exception handler is found then the exception object is passed to the handler code to process the exception, known as
catching the exception.
-If no handler is found, then application throws the exception to runtime environment and JRE terminate the program.
-Compile time errors are not handled by exception handling framework. Only Run time error can only be handled by Exception
Handling framework.
Throws: when we are throwing any exception in a method and not handling it, then we need to use throws keyword in method
signature to let the caller program know the exception that might be thrown by the method.
We can provide multiple exceptions in the throws clause.
Throw: Sometime we want to create an exception object and then throw it to halt the normal processing of the program.Then used
throw keyword .when no record found then throw RecordNotFound Exception.
if(list==null)
{
throw new RecordNotFoundException();
}
Try-Catch: try block contain the code that might cause the exception and catch block can handle the exception created by try block.
Single try block may contain multiple catch exception.
Finally:
-finally, block is optional and can be used only with try catch block.
-finally block will always execute whether exception occurs or not.
-finally block can be useful for resource handling.
Java Exception Hierarchy?
Throwable - is the parent class of java exceptions and it has two child object Error and Exception.
Errors: scenario that are out of scope of application and it’s not possible to recover from them.
Hardware failure and Out of Memory exception.
Exceptions are further divided into checked exception and runtime exception.
Checked Exception: FileNotFoundException we should catch this exception and can provide use full message to the user.
Runtime Exception: caused by bad programming.
ArrayIndexOutOfBoundException
NullPointerException.
ArithmaticException.
Error Exceptions
1 Error are of type ‘Unchecked’. Exception can be either ‘checked’ or ‘unchecked’.
2 Occur at runtime Occur at compile time and runtime
3 Caused by the application running environment. Caused by the application itself.
4 Impossible to recover from error. It is possible to recover from exception using try-catch block.
5
StackOverFlowError: If JVM encounters a situation where there is no space for a new stack frame to be
created, it will throw a StackOverflowError.