Exceptions are the abnormal conditions which generated at the time any runtime error occurred.
To handle these exception is known as exception handling. The exception handling is done to maintain the normal flow of the program. In java there are different types of exceptions checked and unchecked.
The exceptions that are checked at the compiletime are the checked exception and on the other hand the exception that are checked at the runtime are the unchecked exceptions.
lets take an example:
int a= 1/0; // It is a ArithmeticException
The exception handling is done with the help of try catch blocks, the other keywords used in java for exception handling are:
- try.
- catch
- finally
- throw
- throws
Example to show ArithmeticException :
public class ExceptionHandling
{
public static void main(String[] args)
{
System.out.println("statement will get executed");
int a = 1;
try
{
System.out.println(a/0); //This statement throws ArithmeticException
}
catch (Exception e)
{
System.out.println(e);
}
System.out.println("Now, This statement will also be executed");
}
}
In the above code the try catch blocks are used to handle the exception, here the try block throws the exception and the catch block catches it. afterwards the catch block prints the exception i.e., ArithmeticException then at the end the last statement get executed to print the string in it.
The throw keyword throw the exception explicitly. Any method that is capable of listing all the possible exception that can be generated during the execution of the program, this can be done using the throws keyword in any method.
The finally keyword block is used to create a block after the try catch block which gets executed every time whether the exception is generated or not.
This way the exception handling is done with the try catch blocks in java.
0 Comment(s)