Customized Exception handling by try-catch
- It is highly recommended to handle exceptions.
- The code which may raise an exception is call risky code and we have to define that code inside try block and corresponding handling code we have to define inside catch block.
try
{
// Risky code
} catch ( Exception e ) {
// Handling code
}
Control flow in try-catch
Note:
- Within the try block if any where exception raised then rest of the try block would not be executed even though we handle that exception.
- Hence within the try block we have to take only risky code and length of try block should be as less as possible.
- In addition to try block there may be chance of raising an exception inside catch/finally block.
- If any statement which is not part of try-block and raised an exception then it is always abnormal termination.
Method to print Exception information
Ex:
Note:
Internally default exception handler will use printStackTrace() method to print exception information to console.
Try with multiple catch block
The way of handling an exception is varied from exception to exception. Hence for every exception type it is highly recommended to take separate catch block. Means try with multiple catch blocks is always possible and recommended to use.
- If try with multiple block present then the order of catch block is very important. We have to take child first and then parent. Otherwise we will get compile time error, saying
Ex:
- We cannot declare 2 catch blocks for the same exception otherwise we will get compile time exception.