An exception is an abnormal condition that arises in a code sequence at run time. An exception is a run-time error. Most of these run-time errors could be prevented by doing proper input validation as shown in How To Handle An Exception In Java, but in cases where we can not prevent effectively we can use the exception handling mechanism provided by Java.
Shown below is the simplest form of exception handling. Here we have two keywords
try and catch . Just after the try keyword is the try-block and the block after the catch keyword is catch-block.
try { // This is try-block // Include the statements which might cause an exception here } catch(Exception ex) { // This is catch-block // Handle exception here } To understand, the exception handling better lets define a class called ValuableResource . While programming, files, database connections, socket connections etc., are valuable resources. When ever you want to use this ValuableResource , you need create it, initialize it, use it and close it properly before exiting.
Real-life examples of valuable resources are your mobile talk-time, hostel locker etc. When ever we make a call using mobile, we dial the number, talk to the other person and disconnect the call. Similarly, when we use the hostel locker, we open it, put or get the things from it and finally lock it properly. class ValuableResource close() method.
Try Catch Block In Java explains how we can use this resource and communicate to the user regarding the exceptions thrown by it.
|