Exception is a condition. When exception occurs it changes the flow of the program; due to exception the result of the program gets unaccepted to handle such situation and manage the flow of control. Java provides a String mechanism which is known as exception handling.
Exception handling provides the mechanism to handle exception; without proper exception handling if any exception occurs with the program then JVM determines the program and displays the error message.
Throwable is the super class of all exceptions.
Checked exception – those exceptions which are necessary to handle before completion are known as checked exceptions. It is just like a syntax error.
E.g. – IOException.
Unchecked exception
In this type of exception it depends onthe programmer whether he wants to handle the exception or not.
E.g. – ArrayIndexOutOfBoundException, NumberFormatException, AirthmaticException, etc.
Java provide five keyword for exception handling.
- Try
- Catch
- Finally
- Throw
- Throws
Try block:
In try block we write all those statement which can generate any exception. We can handle only those exceptions which occur within try block. If any exception occurs within try block the JRE search the reason of exception then it creates the impliit object of the related class and stores status of the program in the object throws its stand for handling.
Syntax-
Catch block – Exception throw by try block is passed to the catch statement.
Syntax:
- catch (Exception Class Name object )
- {
-
- }
Code written within catch statement is also known as exception handler.
Note – we can use single or more catch with a single try block. Each statement is specified for spared exception.
Syntax:
- try
- {
- }
- catch(------)
- {
- }
- catch(------)
- {
- }
Finally – sometime we need to execute any specific statements which are necessary to execute no matter whether the exception occurs or not. Those statemenst must be written within finally block. Finally block gets executed every time no matter if exception occurs or not.
There are two conditions in which finally block is not executed,
Throw – throw keyword is used to throw user define exception. We can also use this keyword for re-throwing any exception
Throws – when any method is capable of throwing any exception but it doesn’t want to handle it then we use throw keyword after the function prototype. Now it is the responsibility of calling part to property to handle the exception.
Java default handler java itself handles the exception with the help of java default exception handler.
Default exception handler terminates the program and displays the exception message to warning.
Read more articles on Java: