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
In the try-block, we need include the statements which might cause exception, like opening of files, writing data into files or connecting to a remote web server or opening a database connection etc., In the catch-block, we can catch the exception and handle it. Usually in the catch-block we log the exceptions to the log file, so that the admin person knows about it. In the catch block, we will also inform the user of the program about the error in an understandable form.
// This is try-block
// Include the statements which might cause an exception here
// This is catch-block
// Handle exception here
To understand, the exception handling better lets define a class called
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.
For us to effectively use a resource we need to do those steps shown above. But while using the resource, it might throw an exception. We need to handle that exception properly and give a proper message to user. Also we need to close/cleanup the resource by calling the
Try Catch Block In Java explains how we can use this resource and communicate to the user regarding the exceptions thrown by it.