Java Exception Handling : try, catch, final
An exception is an event which that interrupts the normal flow of program. The exception could occur due to any resource required is not available, user enters invalid data , network connection lost etc.
When there is an anomaly during execution of the method, then that method creates an object which contains a lot of debugging information such as method hierarchy, line number where the exception occurred, type of exception etc. The method than pass this object to runtime system which is called throwing an exception.
When the exception is handover to runtime system then it tries to find some catch block which can handle this exception. It tries to find the exception handler block from the method where the exception occurred and proceeds through the call stack in the reverse order in which the methods were called. When it find the block which can handle the type of exception then runtime system passes the exception object to the catch block. If no handler found then the runtime system terminates.
Exception Hierarchy : Throwable is the parent class which has two subclass : Exception and Error
Exceptions are further divided into checked exceptions and runtime exception.
Errors: Errors are the exceptional scenarios which are not in the control of the programmer.
Errors are typically ignored in your code because you can rarely do anything about an error
For example JVM crash, out of memory error, stack overflow.
Checked Exceptions: These are type of exception which we can anticipate and can handle, for example SQL Exception. These type of exception requires being catches and handled during compile time. If Compiler doesn’t see try or catch block handling a Checked Exception, it throws Compilation error.
These exceptions do not extend RuntimeException class and must be handled to avoid a compile-time error by the programmer. All exception which are not subclass of Error or Runtime Exception, are checked exception.
Unchecked Exception :
The classes that extend RuntimeException are known as unchecked exceptions e.g. ArithmeticException. Unchecked exceptions are not checked at compile-time rather they are checked at runtime. In case we are throwing any runtime exception in a method, it’s not required to specify them in the method signature throws clause. Runtime exceptions can be avoided with better programming.
Example
Exception Handling Keywords:
An exception is an event which that interrupts the normal flow of program. The exception could occur due to any resource required is not available, user enters invalid data , network connection lost etc.
When there is an anomaly during execution of the method, then that method creates an object which contains a lot of debugging information such as method hierarchy, line number where the exception occurred, type of exception etc. The method than pass this object to runtime system which is called throwing an exception.
When the exception is handover to runtime system then it tries to find some catch block which can handle this exception. It tries to find the exception handler block from the method where the exception occurred and proceeds through the call stack in the reverse order in which the methods were called. When it find the block which can handle the type of exception then runtime system passes the exception object to the catch block. If no handler found then the runtime system terminates.
Exception Hierarchy : Throwable is the parent class which has two subclass : Exception and Error
Exceptions are further divided into checked exceptions and runtime exception.
Errors: Errors are the exceptional scenarios which are not in the control of the programmer.
Errors are typically ignored in your code because you can rarely do anything about an error
For example JVM crash, out of memory error, stack overflow.
Checked Exceptions: These are type of exception which we can anticipate and can handle, for example SQL Exception. These type of exception requires being catches and handled during compile time. If Compiler doesn’t see try or catch block handling a Checked Exception, it throws Compilation error.
These exceptions do not extend RuntimeException class and must be handled to avoid a compile-time error by the programmer. All exception which are not subclass of Error or Runtime Exception, are checked exception.
Unchecked Exception :
The classes that extend RuntimeException are known as unchecked exceptions e.g. ArithmeticException. Unchecked exceptions are not checked at compile-time rather they are checked at runtime. In case we are throwing any runtime exception in a method, it’s not required to specify them in the method signature throws clause. Runtime exceptions can be avoided with better programming.
Example
import java.io.*;
public class SampleException{
public static void main(String args[]){
try{
int arry[] = new int[4];
System.out.println("Access element Six :" + arry[5]);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("Accessed Element,Out of defined range :" + e);
}
System.out.println("Out of the block");
}
}
There are some specific keywords for exception handling in java.
* throw – It is used to throw exception to the runtime to handle it.* throws – When we throw any exception in a method and not handling it, then we need to use throws keyword in method signature to make caller program aware about the possible exceptions that might be thrown by the method. The caller method might handle these exceptions or propagate it to it’s caller method using throws keyword. We can provide multiple exceptions in the throws clause.
Any Exception that can be thrown by a method is part of the method's public declaration. If any method call this method must handle the checked exception thrown by this method.
* try-catch – try-catch block is used for exception handling in the code. 'try' is the block where a code which may possibly throw exception is executed.
'catch' is used after try block to handle the exceptions.
We can have multiple catch blocks with a try and try-catch block can be nested also.
We need to pass one parameter to catch block of type Exception.
*finally – It is optional and can be used only with try-catch block.
It contains a set of statements that needs to be executed regardless of whether or not any exception occurs in try block.
The code present in the finally block executes even if the try or catch block contains control transfer statements like return, break or continue.
- A try statement should have either catch block or finally block, it can have both blocks.
- catch block must handle exception in the order that subclass is handled first
- We can’t have catch or finally clause without a try statement.
- We can’t write any code between try-catch-finally block.
- We can have multiple catch blocks with a single try statement.
- There can be only one finally block, however there could be multiple catch block for a single try block
There could be any exception in the try block due to which the program flow will jump to catch block so few resources which were opened to use, might keep open.
But if we write those in the catch block, then there could be chance that exception does not occur or the exception occurred may not be of type that the catch block will handle.
If we write the same code in both try and catch that will be duplicate code.
SO we use finally block to write such code which must be executed in all the cases.
finally block may not get executed in case : 1)there is an exception in the finally block 2) System.exit() method is used
Exceptions Methods:
Following is the list of important methods available in the Throwable class.| SN | Methods with Description |
|---|---|
| 1 | public String getMessage() Returns a detailed message about the exception that has occurred. This message is initialized in the Throwable constructor. |
| 2 | public Throwable getCause() Returns the cause of the exception as represented by a Throwable object. |
| 3 | public String toString() Returns the name of the class concatenated with the result of getMessage() |
| 4 | public void printStackTrace() Prints the result of toString() along with the stack trace to System.err, the error output stream. |
| 5 | public StackTraceElement [] getStackTrace() Returns an array containing each element on the stack trace. The element at index 0 represents the top of the call stack, and the last element in the array represents the method at the bottom of the call stack. |
| 6 | public Throwable fillInStackTrace() Fills the stack trace of this Throwable object with the current stack trace, adding to any previous information in the stack trace. |
CUSTOM EXCEPTIONS:
We can create our own exceptions too in java. We can create exception corresponding to any condition which we feel that is not normal as per our application behaviour.
For example : We can create exception if the Mobile number entered is not in the format
+CC xxx-yyy-zzzz
We should keep the following things in mind while planning our own exception type:
* Every exception/error is child of Throwable class
* If we want that the exception must be handled than we can extend the Exception class otherwise for unchecked exception we can extend the Runtime Class

Comments
Post a Comment