What are exceptions? Why is it important to handle exceptions? Discuss different keywords that are used to handle exceptions.
An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception occurs the normal flow of the program is disrupted and the program/Application terminates abnormally, which is not recommended, therefore, these exceptions are to be handled.
Importance of handling exceptions.
● First, it lets the user know, in a relatively friendly manner, that something has gone wrong and that they should contact the technical support department or that someone from tech support has been notified. As we all know there's a HUGE difference between receiving a rather nasty, tech riddled notice that says something like "Object not set to reference of an object" etc. ... and receiving a nice popup type window that says "There has been an issue. Please contact the helpdesk".
● Second, it allows the programmer to put in some niceties to aid in the debugging of issues. For instance ... in my code, I typically write a custom error handler that takes in a number of parameters and spits back a nice, formatted message that can either be emailed to the helpdesk, stashed in an event log, written to a log file etc.. The error message will contain as much info as I can cram in there to help me figure out what happened, stack traces, function parameters, database calls ... you name it. I like verbose error messages to help me figure out what actually happened. The user never has to see any of it, they get the nice, friendly message above, letting them know that someone can figure out what's going on.
There are five keywords used in Java for exception handling. They are:
i. try
ii. catch
iii. throw
iv. throws
v. finally
The try block
The try block contains the code that might throw an exception. The try block contains at least one catch block or finally block.
The catch block
A catch block must be declared after try block. It contains the error handling code. A catch block executes if an exception generates in corresponding try block.
The throw keyword in Java
● The throw keyword in Java is used to explicitly throw our own exception.
● It can be used for both checked and unchecked exception.
The throws keyword in Java
● The throws keyword is generally used for handling checked exception.
● When you do not want to handle a program by try and catch block, it can be handled by throws.
● Without handling checked exceptions program can never be compiled.
● The throws keyword is always added after the method signature.
The finally block
● The code present in finally block will always be executed even if try block generates some exception.
● Finally block must be followed by try or catch block.
● It is used to execute some important code.
● Finally block executes after try and catch block
Comments
Post a Comment