No matter how efficient you coding skills are, errors are bound to occurs, sometimes it could be as simple as forgetting a semicolon or brackets. Other times, it could be that it input for the certain function is not the right data type. So, it is always a good practice to anticipate these errors and try to deal with them rather than shutting down the whole application; that’s exactly the case if we don’t handle these errors. Exception handling allows us to handle errors gracefully. When a code runs into a problem, an exception raised (or thrown). We can achieve this by using try, catch and throw keywords.
Let us look at the example, imagine we are getting an input from the user and doing something with that input. But, before we process this input, let’s assume that there are conditions that have to be met. The conditions are, input have to be a numerical value, cannot be empty and has to be in range 1 to 100. We can enforce the conditions by using this example:
Try gives us the block of codes that we can test for the errors and once the error is found, throw keyword throws that error and contents of catch block is executed. In this case, we can print out “success!” only when we are met with no error, otherwise the execution shifts to the catch block.
Another, keyword that is usually associated with exception handling is finally. Code block inside finally is always executed, even when there is no error in the try block and usually comes after the catch block. The syntax looks something like this:
One of the common example when finally is very useful is when the program is reading and writing to a file resource. Usually we open a file resource and attempt to write something on the file resource and it is always a good practice to close the resource even when we encounter the error and in this case the code block to close the resource should go inside the finally block.