Point to remember regarding try- catch:
- Whenever try block has n number of blocks, then if an exception object is created, the order of preference of catch blocks is the order in which they are present below the try block.
Consider the following scenarios:
Catch (exceptions e)
System .out. println (e);
Catch (Arithmetic Exception e1)
System .out. println (e1);
} -----> Unreached blocks
Catch (null point Exception e2)
System .out. println (e2);
- Now, if at all an exception is raised in a try block, it will be transferred to the immediate catch block. If that catch block is not capable of handling that exception, then it is transferred to the next catch block and so on.
- In the example, the very first catch block is a catch (Exception e). Since exception class is the superclass of all exceptions classes, its reference will be capable of receiving any exception class objects.
- Thus, in the above program, the remaining catch blocks are not going to get executed at any instance of time.
- Such blocks which are not going to get executed at any instance of time are known as unreachable blocks.
- Unreachable blocks are not supported by java. Hence, whenever we compile a source code, the compiler searches for unreachable blocks in the source code. If it finds any, it gives a complication error.
Whenever we need to define multiple catch blocks and if catch (exception e) is one among those, then we should see that catch (exception e) will be the last catch block in that group of multiple catch blocks.
Try catch block Homework Help