Try Catch Block in Java

we have discussed what is exception handling in java, now we will see the different types of block statements used for exception handling
Try block
Try block contains a set of statements where the exception might occur. A try block must be followed by either a catch block or finally block. a catch block handles the exception occurred from the try block
Syntax
Catch block
Catch block is used to handle exceptions from the try block. Catch block must followed by the try block. catch block contains two parameters ,type of the exception and exception object name. there can multiple catch statements for the single try block
Example for try-catch block
Output
In the above example, in try block we have divided a number 20 with 0, this raises a arithmetic exception, so the catch block parameter we have used ArithmeticException as the exception type and the object as e, so when this code is executed the exception name will be displayed and then the rest of the code which is present below the catch block will be executed
you may have observed above that the print statement after the exception (25 / 0) did int got in the output because, the statements below the exception caused line will not be executed
Multiple Catch blocks
As we know already a single try block can have multiple catch blocks. below are some points regarding mutiple catch blocks
- A single try block can have any number of catch blocks
- First, is the try block followed by catch blocks
- Multiple catch blocks are used to handle each exception separately
- There is a generic catch block, which can handle every type of exception
- if there is no exception occurred in the try block the, the catch blocks are ignored
- each catch block can have ist won type of exception
Generic catch block syntax
we can use only generic exception catch block for all exceptions,but this cannot identify which exception has occurred in the try block
for example, if there is an ArithmeticException and NullPointerException both occur in the try block, so if we use a generic catch block, the output display message will be the same for both of these exceptions, so the user may not identify which exception has caused the program to terminate. so this generic catch block should be placed as the last catch block
info
generic exception catch block should be always a last catch block, or else it will override its following catch blocks
Multiple catch blocks Example (placing generic catch block at beginning)
Output
In the above program, generic catch block is placed at the top of the ArrayIndexOutOfBoundsException so ,the program throws error stating “exception ArrayIndexOutOfBoundsException has already been caught”