An exception 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 terminates abnormally, which is not recommended. The mechanism to handle such scenarios known as Exception Handling.
Few exceptions are NullPointerException, ClassNotFoundException, IOException, SQLException, RemoteException etc.
Advantage of Exception Handling
The main advantage of exception handling is to maintain the normal flow of the application. See the scenario below.
Suppose there are 5 statements in Java program and there occurs an exception at statement 3, the rest of the code will not be executed i.e. statement 4 and 5 will not be executed. However, we can be executed the rest of the statement by exception handling.
Java Exception Handling Keywords
Java provides specific keywords for exception handling purposes. See the list below.
try-catch – try-catch block is used to handle exception in code. try is the start of the block and catch is at the end of try block to handle the exceptions. try block can have multiple catch blocks and try-catch block can be nested also. catch block requires a parameter that should be of type or subtype Exception.
try-multiple catch example
try-multiple catch Java 7 example
After Java 7 release, we can club multiple catches using pipeline separator.
finally – finally block is optional and can be used only with try or try-catch block. Since exception halts the process of execution, the program might have some resources open that will not get closed, so it can be closed in finally block as finally block executed always, whether an exception occurred or not.
throw – If any exception occurs, an exception object is getting created and then Java runtime starts processing to handle them. Sometime it might require to generate exception explicitly in code, for example in user authentication, the program should throw an exception to the client if the password is null. throw keyword is used to throw an exception to the runtime to handle it.
throws – When the program is throwing an exception in a method and no need to handle it, throws keyword need to use in method signature to let the caller program know the exceptions that might be thrown by the method. The caller method might handle these exceptions or propagate it to its caller method using throws keyword. Multiple exceptions can provide in the throws clause and it can be used with main() method also.