Java Exception handling:
There are 5 keywords related to Exception Handling; those are
We can use 3 combination of try-catch-finally in Java methods; those combination are
throw and throws (with an extra S):
- throw is used to throw exception from executing block; it could be try-block or catch-block (from inside a method)
- throws is used to indicate that particular method is possibly throws these exceptions; again method can throws any number of exceptions
Difference between throws clause and try-catch block ?
- As explained above, throws clause is used to indicate that particular exception is possibly thrown from executing method at run-time
- Whereas try-catch block is used to handle exception scenario
- Like, if any particular exception is thrown from try block;
- then corresponding catch-block catches that particular exception and we can take necessary action from there ON (this is some kind of coding stuff)
|try-catch block||throws keyword|
|Using try-catch block, we can handle exception surrounding code that might raise an exception||Whereas using throws keyword, we can simply declare exception that might raise from that method|
|Caught exception in the catch block can be re-thrown after some alteration||There is no such flexibility, as its directly throws exception|
|try-catch block ensures graceful termination for that particular method
Except one scenario when catch block throws exception
|Doesn’t guarantee graceful termination
In most cases, throws declaration leads to abnormal termination
Hope, it help to understand most of the things related to Java Exception Handling
Happy Coding !!
Happy Learning !!